├── .coveragerc ├── .gitattributes ├── .github ├── CODEOWNERS ├── pull_request_template.md ├── stale.yml └── workflows │ ├── build.yml │ ├── directory_writer.yml │ ├── pre-commit.yml │ └── project_euler.yml ├── .gitignore ├── .gitpod.yml ├── .pre-commit-config.yaml ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE.md ├── README.md ├── arithmetic_analysis ├── __init__.py ├── bisection.py ├── gaussian_elimination.py ├── image_data │ ├── 2D_problems.jpg │ ├── 2D_problems_1.jpg │ └── __init__.py ├── in_static_equilibrium.py ├── intersection.py ├── lu_decomposition.py ├── newton_forward_interpolation.py ├── newton_method.py ├── newton_raphson.py └── secant_method.py ├── backtracking ├── __init__.py ├── all_combinations.py ├── all_permutations.py ├── all_subsequences.py ├── coloring.py ├── hamiltonian_cycle.py ├── knight_tour.py ├── minimax.py ├── n_queens.py ├── n_queens_math.py ├── rat_in_maze.py ├── sudoku.py └── sum_of_subsets.py ├── bit_manipulation ├── README.md ├── __init__.py ├── binary_and_operator.py ├── binary_count_setbits.py ├── binary_count_trailing_zeros.py ├── binary_or_operator.py ├── binary_xor_operator.py └── single_bit_manipulation_operations.py ├── blockchain ├── __init__.py ├── chinese_remainder_theorem.py ├── diophantine_equation.py └── modular_division.py ├── boolean_algebra ├── __init__.py └── quine_mc_cluskey.py ├── cellular_automata ├── README.md ├── __init__.py └── one_dimensional.py ├── ciphers ├── __init__.py ├── a1z26.py ├── affine_cipher.py ├── atbash.py ├── base16.py ├── base32.py ├── base64_encoding.py ├── base85.py ├── beaufort_cipher.py ├── brute_force_caesar_cipher.py ├── caesar_cipher.py ├── cryptomath_module.py ├── decrypt_caesar_with_chi_squared.py ├── deterministic_miller_rabin.py ├── diffie.py ├── elgamal_key_generator.py ├── enigma_machine2.py ├── hill_cipher.py ├── mixed_keyword_cypher.py ├── mono_alphabetic_ciphers.py ├── morse_code_implementation.py ├── onepad_cipher.py ├── playfair_cipher.py ├── porta_cipher.py ├── prehistoric_men.txt ├── rabin_miller.py ├── rail_fence_cipher.py ├── rot13.py ├── rsa_cipher.py ├── rsa_factorization.py ├── rsa_key_generator.py ├── shuffled_shift_cipher.py ├── simple_keyword_cypher.py ├── simple_substitution_cipher.py ├── trafid_cipher.py ├── transposition_cipher.py ├── transposition_cipher_encrypt_decrypt_file.py ├── vigenere_cipher.py └── xor_cipher.py ├── compression ├── __init__.py ├── burrows_wheeler.py ├── huffman.py ├── image_data │ ├── PSNR-example-base.png │ ├── PSNR-example-comp-10.jpg │ ├── __init__.py │ ├── compressed_image.png │ ├── example_image.jpg │ ├── example_wikipedia_image.jpg │ └── original_image.png ├── lempel_ziv.py ├── lempel_ziv_decompress.py └── peak_signal_to_noise_ratio.py ├── computer_vision ├── README.md ├── __init__.py ├── harriscorner.py └── meanthreshold.py ├── conversions ├── __init__.py ├── binary_to_decimal.py ├── binary_to_octal.py ├── decimal_to_any.py ├── decimal_to_binary.py ├── decimal_to_binary_recursion.py ├── decimal_to_hexadecimal.py ├── decimal_to_octal.py ├── hexadecimal_to_decimal.py ├── molecular_chemistry.py ├── octal_to_decimal.py ├── prefix_conversions.py ├── roman_to_integer.py ├── temperature_conversions.py └── weight_conversion.py ├── data_structures ├── __init__.py ├── binary_tree │ ├── __init__.py │ ├── avl_tree.py │ ├── basic_binary_tree.py │ ├── binary_search_tree.py │ ├── binary_search_tree_recursive.py │ ├── binary_tree_mirror.py │ ├── binary_tree_traversals.py │ ├── fenwick_tree.py │ ├── lazy_segment_tree.py │ ├── lowest_common_ancestor.py │ ├── non_recursive_segment_tree.py │ ├── number_of_possible_binary_trees.py │ ├── red_black_tree.py │ ├── segment_tree.py │ ├── segment_tree_other.py │ └── treap.py ├── disjoint_set │ ├── __init__.py │ ├── alternate_disjoint_set.py │ └── disjoint_set.py ├── hashing │ ├── __init__.py │ ├── double_hash.py │ ├── hash_table.py │ ├── hash_table_with_linked_list.py │ ├── number_theory │ │ ├── __init__.py │ │ └── prime_numbers.py │ └── quadratic_probing.py ├── heap │ ├── __init__.py │ ├── binomial_heap.py │ ├── heap.py │ ├── heap_generic.py │ ├── max_heap.py │ ├── min_heap.py │ ├── randomized_heap.py │ └── skew_heap.py ├── linked_list │ ├── __init__.py │ ├── circular_linked_list.py │ ├── deque_doubly.py │ ├── doubly_linked_list.py │ ├── doubly_linked_list_two.py │ ├── from_sequence.py │ ├── has_loop.py │ ├── is_palindrome.py │ ├── middle_element_of_linked_list.py │ ├── print_reverse.py │ ├── singly_linked_list.py │ ├── skip_list.py │ └── swap_nodes.py ├── queue │ ├── __init__.py │ ├── circular_queue.py │ ├── double_ended_queue.py │ ├── linked_queue.py │ ├── priority_queue_using_list.py │ ├── queue_on_list.py │ └── queue_on_pseudo_stack.py ├── stacks │ ├── __init__.py │ ├── balanced_parentheses.py │ ├── dijkstras_two_stack_algorithm.py │ ├── evaluate_postfix_notations.py │ ├── infix_to_postfix_conversion.py │ ├── infix_to_prefix_conversion.py │ ├── linked_stack.py │ ├── next_greater_element.py │ ├── postfix_evaluation.py │ ├── prefix_evaluation.py │ ├── stack.py │ ├── stack_using_dll.py │ └── stock_span_problem.py └── trie │ ├── __init__.py │ └── trie.py ├── digital_image_processing ├── __init__.py ├── change_brightness.py ├── change_contrast.py ├── convert_to_negative.py ├── dithering │ ├── __init__.py │ └── burkes.py ├── edge_detection │ ├── __init__.py │ └── canny.py ├── filters │ ├── __init__.py │ ├── bilateral_filter.py │ ├── convolve.py │ ├── gaussian_filter.py │ ├── median_filter.py │ └── sobel_filter.py ├── histogram_equalization │ ├── __init__.py │ ├── histogram_stretch.py │ ├── image_data │ │ ├── __init__.py │ │ └── input.jpg │ └── output_data │ │ ├── __init__.py │ │ └── output.jpg ├── image_data │ ├── __init__.py │ ├── lena.jpg │ └── lena_small.jpg ├── index_calculation.py ├── resize │ ├── __init__.py │ └── resize.py ├── rotation │ ├── __init__.py │ └── rotation.py ├── sepia.py └── test_digital_image_processing.py ├── divide_and_conquer ├── __init__.py ├── closest_pair_of_points.py ├── convex_hull.py ├── heaps_algorithm.py ├── heaps_algorithm_iterative.py ├── inversions.py ├── kth_order_statistic.py ├── max_difference_pair.py ├── max_subarray_sum.py ├── mergesort.py ├── peak.py ├── power.py └── strassen_matrix_multiplication.py ├── dynamic_programming ├── __init__.py ├── abbreviation.py ├── bitmask.py ├── climbing_stairs.py ├── coin_change.py ├── edit_distance.py ├── factorial.py ├── fast_fibonacci.py ├── fibonacci.py ├── floyd_warshall.py ├── fractional_knapsack.py ├── fractional_knapsack_2.py ├── integer_partition.py ├── iterating_through_submasks.py ├── k_means_clustering_tensorflow.py_tf ├── knapsack.py ├── longest_common_subsequence.py ├── longest_increasing_subsequence.py ├── longest_increasing_subsequence_o(nlogn).py ├── longest_sub_array.py ├── matrix_chain_order.py ├── max_non_adjacent_sum.py ├── max_sub_array.py ├── max_sum_contiguous_subsequence.py ├── minimum_cost_path.py ├── minimum_partition.py ├── optimal_binary_search_tree.py ├── rod_cutting.py ├── subset_generation.py └── sum_of_subset.py ├── electronics └── ohms_law.py ├── file_transfer ├── __init__.py ├── mytext.txt ├── receive_file.py ├── send_file.py └── tests │ ├── __init__.py │ └── test_send_file.py ├── fuzzy_logic ├── __init__.py └── fuzzy_operations.py ├── genetic_algorithm ├── __init__.py └── basic_string.py ├── geodesy ├── __init__.py ├── haversine_distance.py └── lamberts_ellipsoidal_distance.py ├── graphics ├── __init__.py ├── bezier_curve.py └── vector3_for_2d_rendering.py ├── graphs ├── __init__.py ├── a_star.py ├── articulation_points.py ├── basic_graphs.py ├── bellman_ford.py ├── bfs_shortest_path.py ├── bfs_zero_one_shortest_path.py ├── bidirectional_a_star.py ├── bidirectional_breadth_first_search.py ├── breadth_first_search.py ├── breadth_first_search_2.py ├── breadth_first_search_shortest_path.py ├── check_bipartite_graph_bfs.py ├── check_bipartite_graph_dfs.py ├── connected_components.py ├── depth_first_search.py ├── depth_first_search_2.py ├── dijkstra.py ├── dijkstra_2.py ├── dijkstra_algorithm.py ├── dinic.py ├── directed_and_undirected_(weighted)_graph.py ├── edmonds_karp_multiple_source_and_sink.py ├── eulerian_path_and_circuit_for_undirected_graph.py ├── even_tree.py ├── finding_bridges.py ├── frequent_pattern_graph_miner.py ├── g_topological_sort.py ├── gale_shapley_bigraph.py ├── graph_list.py ├── graph_matrix.py ├── graphs_floyd_warshall.py ├── greedy_best_first.py ├── kahns_algorithm_long.py ├── kahns_algorithm_topo.py ├── karger.py ├── minimum_spanning_tree_boruvka.py ├── minimum_spanning_tree_kruskal.py ├── minimum_spanning_tree_kruskal2.py ├── minimum_spanning_tree_prims.py ├── minimum_spanning_tree_prims2.py ├── multi_heuristic_astar.py ├── page_rank.py ├── prim.py ├── scc_kosaraju.py ├── strongly_connected_components.py ├── tarjans_scc.py └── tests │ ├── test_min_spanning_tree_kruskal.py │ └── test_min_spanning_tree_prim.py ├── hashes ├── __init__.py ├── adler32.py ├── chaos_machine.py ├── djb2.py ├── enigma_machine.py ├── hamming_code.py ├── md5.py ├── sdbm.py └── sha1.py ├── knapsack ├── README.md ├── __init__.py ├── greedy_knapsack.py ├── knapsack.py └── tests │ ├── __init__.py │ ├── test_greedy_knapsack.py │ └── test_knapsack.py ├── linear_algebra ├── README.md ├── __init__.py └── src │ ├── __init__.py │ ├── lib.py │ ├── polynom_for_points.py │ ├── power_iteration.py │ ├── rayleigh_quotient.py │ ├── test_linear_algebra.py │ └── transformations_2d.py ├── machine_learning ├── __init__.py ├── astar.py ├── data_transformations.py ├── decision_tree.py ├── forecasting │ ├── __init__.py │ ├── ex_data.csv │ └── run.py ├── gaussian_naive_bayes.py ├── gradient_boosting_regressor.py ├── gradient_descent.py ├── k_means_clust.py ├── k_nearest_neighbours.py ├── knn_sklearn.py ├── linear_discriminant_analysis.py ├── linear_regression.py ├── logistic_regression.py ├── lstm │ ├── __init__.py │ ├── lstm_prediction.py_tf │ └── sample_data.csv ├── multilayer_perceptron_classifier.py ├── polymonial_regression.py ├── random_forest_classifier.py ├── random_forest_regressor.py ├── scoring_functions.py ├── sequential_minimum_optimization.py ├── similarity_search.py ├── support_vector_machines.py └── word_frequency_functions.py ├── maths ├── 3n_plus_1.py ├── __init__.py ├── abs.py ├── abs_max.py ├── abs_min.py ├── add.py ├── aliquot_sum.py ├── allocation_number.py ├── area.py ├── area_under_curve.py ├── armstrong_numbers.py ├── average_mean.py ├── average_median.py ├── average_mode.py ├── bailey_borwein_plouffe.py ├── basic_maths.py ├── binary_exp_mod.py ├── binary_exponentiation.py ├── binomial_coefficient.py ├── binomial_distribution.py ├── bisection.py ├── ceil.py ├── chudnovsky_algorithm.py ├── collatz_sequence.py ├── combinations.py ├── decimal_isolate.py ├── entropy.py ├── euclidean_distance.py ├── eulers_totient.py ├── explicit_euler.py ├── extended_euclidean_algorithm.py ├── factorial_iterative.py ├── factorial_python.py ├── factorial_recursive.py ├── factors.py ├── fermat_little_theorem.py ├── fibonacci.py ├── fibonacci_sequence_recursion.py ├── find_max.py ├── find_max_recursion.py ├── find_min.py ├── find_min_recursion.py ├── floor.py ├── gamma.py ├── gaussian.py ├── greatest_common_divisor.py ├── hardy_ramanujanalgo.py ├── images │ ├── __init__.py │ └── gaussian.png ├── is_square_free.py ├── jaccard_similarity.py ├── kadanes.py ├── karatsuba.py ├── krishnamurthy_number.py ├── kth_lexicographic_permutation.py ├── largest_of_very_large_numbers.py ├── least_common_multiple.py ├── line_length.py ├── lucas_lehmer_primality_test.py ├── lucas_series.py ├── matrix_exponentiation.py ├── miller_rabin.py ├── mobius_function.py ├── modular_exponential.py ├── monte_carlo.py ├── monte_carlo_dice.py ├── newton_raphson.py ├── number_of_digits.py ├── numerical_integration.py ├── perfect_cube.py ├── perfect_number.py ├── perfect_square.py ├── pi_monte_carlo_estimation.py ├── polynomial_evaluation.py ├── power_using_recursion.py ├── prime_check.py ├── prime_factors.py ├── prime_numbers.py ├── prime_sieve_eratosthenes.py ├── pythagoras.py ├── qr_decomposition.py ├── quadratic_equations_complex_numbers.py ├── radians.py ├── radix2_fft.py ├── relu.py ├── runge_kutta.py ├── segmented_sieve.py ├── series │ ├── __init__.py │ ├── geometric_series.py │ ├── harmonic_series.py │ └── p_series.py ├── sieve_of_eratosthenes.py ├── sigmoid.py ├── simpson_rule.py ├── softmax.py ├── square_root.py ├── sum_of_arithmetic_series.py ├── sum_of_digits.py ├── sum_of_geometric_progression.py ├── test_prime_check.py ├── trapezoidal_rule.py ├── ugly_numbers.py ├── volume.py └── zellers_congruence.py ├── matrix ├── __init__.py ├── count_islands_in_matrix.py ├── inverse_of_matrix.py ├── matrix_class.py ├── matrix_operation.py ├── nth_fibonacci_using_matrix_exponentiation.py ├── rotate_matrix.py ├── searching_in_sorted_matrix.py ├── sherman_morrison.py ├── spiral_print.py └── tests │ ├── __init__.py │ ├── pytest.ini │ └── test_matrix_operation.py ├── networking_flow ├── __init__.py ├── ford_fulkerson.py └── minimum_cut.py ├── neural_network ├── __init__.py ├── back_propagation_neural_network.py ├── convolution_neural_network.py ├── gan.py_tf ├── input_data.py_tf └── perceptron.py ├── other ├── __init__.py ├── activity_selection.py ├── anagrams.py ├── autocomplete_using_trie.py ├── binary_exponentiation.py ├── binary_exponentiation_2.py ├── davis–putnam–logemann–loveland.py ├── detecting_english_programmatically.py ├── dictionary.txt ├── dijkstra_bankers_algorithm.py ├── doomsday.py ├── euclidean_gcd.py ├── fischer_yates_shuffle.py ├── frequency_finder.py ├── game_of_life.py ├── gauss_easter.py ├── greedy.py ├── integeration_by_simpson_approx.py ├── largest_subarray_sum.py ├── least_recently_used.py ├── lfu_cache.py ├── linear_congruential_generator.py ├── lru_cache.py ├── magicdiamondpattern.py ├── markov_chain.py ├── max_sum_sliding_window.py ├── median_of_two_arrays.py ├── nested_brackets.py ├── palindrome.py ├── password_generator.py ├── primelib.py ├── scoring_algorithm.py ├── sdes.py ├── sierpinski_triangle.py ├── tower_of_hanoi.py ├── triplet_sum.py ├── two_pointer.py ├── two_sum.py ├── word_patterns.py └── words ├── project_euler ├── README.md ├── __init__.py ├── problem_001 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ ├── sol4.py │ ├── sol5.py │ ├── sol6.py │ └── sol7.py ├── problem_002 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ ├── sol4.py │ └── sol5.py ├── problem_003 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_004 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_005 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_006 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ └── sol4.py ├── problem_007 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_008 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_009 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_010 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_011 │ ├── __init__.py │ ├── grid.txt │ ├── sol1.py │ └── sol2.py ├── problem_012 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_013 │ ├── __init__.py │ ├── num.txt │ └── sol1.py ├── problem_014 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_015 │ ├── __init__.py │ └── sol1.py ├── problem_016 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_017 │ ├── __init__.py │ └── sol1.py ├── problem_018 │ ├── __init__.py │ ├── solution.py │ └── triangle.txt ├── problem_019 │ ├── __init__.py │ └── sol1.py ├── problem_020 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ └── sol4.py ├── problem_021 │ ├── __init__.py │ └── sol1.py ├── problem_022 │ ├── __init__.py │ ├── p022_names.txt │ ├── sol1.py │ └── sol2.py ├── problem_023 │ ├── __init__.py │ └── sol1.py ├── problem_024 │ ├── __init__.py │ └── sol1.py ├── problem_025 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_026 │ ├── __init__.py │ └── sol1.py ├── problem_027 │ ├── __init__.py │ └── sol1.py ├── problem_028 │ ├── __init__.py │ └── sol1.py ├── problem_029 │ ├── __init__.py │ └── sol1.py ├── problem_030 │ ├── __init__.py │ └── sol1.py ├── problem_031 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_032 │ ├── __init__.py │ └── sol32.py ├── problem_033 │ ├── __init__.py │ └── sol1.py ├── problem_034 │ ├── __init__.py │ └── sol1.py ├── problem_035 │ ├── __init__.py │ └── sol1.py ├── problem_036 │ ├── __init__.py │ └── sol1.py ├── problem_037 │ ├── __init__.py │ └── sol1.py ├── problem_038 │ ├── __init__.py │ └── sol1.py ├── problem_039 │ ├── __init__.py │ └── sol1.py ├── problem_040 │ ├── __init__.py │ └── sol1.py ├── problem_041 │ ├── __init__.py │ └── sol1.py ├── problem_042 │ ├── __init__.py │ ├── solution42.py │ └── words.txt ├── problem_043 │ ├── __init__.py │ └── sol1.py ├── problem_044 │ ├── __init__.py │ └── sol1.py ├── problem_045 │ ├── __init__.py │ └── sol1.py ├── problem_046 │ ├── __init__.py │ └── sol1.py ├── problem_047 │ ├── __init__.py │ └── sol1.py ├── problem_048 │ ├── __init__.py │ └── sol1.py ├── problem_049 │ ├── __init__.py │ └── sol1.py ├── problem_050 │ ├── __init__.py │ └── sol1.py ├── problem_051 │ ├── __init__.py │ └── sol1.py ├── problem_052 │ ├── __init__.py │ └── sol1.py ├── problem_053 │ ├── __init__.py │ └── sol1.py ├── problem_054 │ ├── __init__.py │ ├── poker_hands.txt │ ├── sol1.py │ └── test_poker_hand.py ├── problem_055 │ ├── __init__.py │ └── sol1.py ├── problem_056 │ ├── __init__.py │ └── sol1.py ├── problem_057 │ ├── __init__.py │ └── sol1.py ├── problem_058 │ ├── __init__.py │ └── sol1.py ├── problem_062 │ ├── __init__.py │ └── sol1.py ├── problem_063 │ ├── __init__.py │ └── sol1.py ├── problem_064 │ ├── __init__.py │ └── sol1.py ├── problem_065 │ ├── __init__.py │ └── sol1.py ├── problem_067 │ ├── __init__.py │ ├── sol1.py │ └── triangle.txt ├── problem_069 │ ├── __init__.py │ └── sol1.py ├── problem_070 │ ├── __init__.py │ └── sol1.py ├── problem_071 │ ├── __init__.py │ └── sol1.py ├── problem_072 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_074 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_075 │ ├── __init__.py │ └── sol1.py ├── problem_076 │ ├── __init__.py │ └── sol1.py ├── problem_077 │ ├── __init__.py │ └── sol1.py ├── problem_080 │ ├── __init__.py │ └── sol1.py ├── problem_081 │ ├── __init__.py │ ├── matrix.txt │ └── sol1.py ├── problem_087 │ ├── __init__.py │ └── sol1.py ├── problem_089 │ ├── __init__.py │ ├── numeralcleanup_test.txt │ ├── p089_roman.txt │ └── sol1.py ├── problem_091 │ ├── __init__.py │ └── sol1.py ├── problem_097 │ ├── __init__.py │ └── sol1.py ├── problem_099 │ ├── __init__.py │ ├── base_exp.txt │ └── sol1.py ├── problem_112 │ ├── __init__.py │ └── sol1.py ├── problem_113 │ ├── __init__.py │ └── sol1.py ├── problem_119 │ ├── __init__.py │ └── sol1.py ├── problem_120 │ ├── __init__.py │ └── sol1.py ├── problem_123 │ ├── __init__.py │ └── sol1.py ├── problem_125 │ ├── __init__.py │ └── sol1.py ├── problem_129 │ ├── __init__.py │ └── sol1.py ├── problem_173 │ ├── __init__.py │ └── sol1.py ├── problem_174 │ ├── __init__.py │ └── sol1.py ├── problem_188 │ ├── __init__.py │ └── sol1.py ├── problem_191 │ ├── __init__.py │ └── sol1.py ├── problem_203 │ ├── __init__.py │ └── sol1.py ├── problem_206 │ ├── __init__.py │ └── sol1.py ├── problem_207 │ ├── __init__.py │ └── sol1.py ├── problem_234 │ ├── __init__.py │ └── sol1.py ├── problem_301 │ ├── __init__.py │ └── sol1.py └── problem_551 │ ├── __init__.py │ └── sol1.py ├── pytest.ini ├── quantum ├── README.md ├── __init__.py ├── deutsch_jozsa.py ├── half_adder.py ├── not_gate.py ├── quantum_entanglement.py ├── ripple_adder_classic.py └── single_qubit_measure.py ├── requirements.txt ├── scheduling ├── __init__.py ├── first_come_first_served.py ├── round_robin.py └── shortest_job_first.py ├── scripts ├── __init__.py ├── build_directory_md.py ├── project_euler_answers.json ├── validate_filenames.py └── validate_solutions.py ├── searches ├── __init__.py ├── binary_search.py ├── double_linear_search.py ├── double_linear_search_recursion.py ├── fibonacci_search.py ├── hill_climbing.py ├── interpolation_search.py ├── jump_search.py ├── linear_search.py ├── quick_select.py ├── sentinel_linear_search.py ├── simple_binary_search.py ├── simulated_annealing.py ├── tabu_search.py ├── tabu_test_data.txt └── ternary_search.py ├── sorts ├── __init__.py ├── bead_sort.py ├── bitonic_sort.py ├── bogo_sort.py ├── bubble_sort.py ├── bucket_sort.py ├── cocktail_shaker_sort.py ├── comb_sort.py ├── counting_sort.py ├── cycle_sort.py ├── double_sort.py ├── external_sort.py ├── gnome_sort.py ├── heap_sort.py ├── insertion_sort.py ├── intro_sort.py ├── iterative_merge_sort.py ├── merge_insertion_sort.py ├── merge_sort.py ├── natural_sort.py ├── normal_distribution_quick_sort.md ├── odd_even_transposition_parallel.py ├── odd_even_transposition_single_threaded.py ├── pancake_sort.py ├── patience_sort.py ├── pigeon_sort.py ├── pigeonhole_sort.py ├── quick_sort.py ├── quick_sort_3_partition.py ├── radix_sort.py ├── random_normal_distribution_quicksort.py ├── random_pivot_quick_sort.py ├── recursive_bubble_sort.py ├── recursive_insertion_sort.py ├── recursive_quick_sort.py ├── selection_sort.py ├── shell_sort.py ├── stooge_sort.py ├── strand_sort.py ├── tim_sort.py ├── topological_sort.py ├── tree_sort.py ├── unknown_sort.py └── wiggle_sort.py ├── strings ├── __init__.py ├── aho_corasick.py ├── boyer_moore_search.py ├── can_string_be_rearranged_as_palindrome.py ├── capitalize.py ├── check_anagrams.py ├── check_pangram.py ├── is_palindrome.py ├── jaro_winkler.py ├── knuth_morris_pratt.py ├── levenshtein_distance.py ├── lower.py ├── manacher.py ├── min_cost_string_conversion.py ├── naive_string_search.py ├── prefix_function.py ├── rabin_karp.py ├── remove_duplicate.py ├── reverse_letters.py ├── reverse_words.py ├── split.py ├── swap_case.py ├── upper.py ├── word_occurrence.py └── z_function.py ├── traversals ├── __init__.py └── binary_tree_traversals.py └── web_programming ├── __init__.py ├── co2_emission.py ├── covid_stats_via_xpath.py ├── crawl_google_results.py ├── crawl_google_scholar_citation.py ├── currency_converter.py ├── current_stock_price.py ├── current_weather.py ├── daily_horoscope.py ├── emails_from_url.py ├── fetch_bbc_news.py ├── fetch_github_info.py ├── fetch_jobs.py ├── get_imdb_top_250_movies_csv.py ├── get_imdbtop.py ├── instagram_crawler.py ├── instagram_pic.py ├── recaptcha_verification.py ├── slack_message.py ├── test_fetch_github_info.py └── world_covid19_stats.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | sort = Cover 3 | omit = 4 | .env/* 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: "build" 2 | 3 | on: 4 | pull_request: 5 | schedule: 6 | - cron: "0 0 * * *" # Run everyday 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-python@v2 14 | with: 15 | python-version: "3.9" 16 | - uses: actions/cache@v2 17 | with: 18 | path: ~/.cache/pip 19 | key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip setuptools six wheel 23 | python -m pip install pytest-cov -r requirements.txt 24 | - name: Run tests 25 | run: pytest --doctest-modules --ignore=project_euler/ --cov-report=term-missing:skip-covered --cov=. . 26 | - if: ${{ success() }} 27 | run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md 28 | -------------------------------------------------------------------------------- /.github/workflows/directory_writer.yml: -------------------------------------------------------------------------------- 1 | # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) 2 | # when doing a git push 3 | name: directory_writer 4 | on: [push] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 # v1, NOT v2 10 | - uses: actions/setup-python@v2 11 | - name: Write DIRECTORY.md 12 | run: | 13 | scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md 14 | git config --global user.name github-actions 15 | git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' 16 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 17 | - name: Update DIRECTORY.md 18 | run: | 19 | git add DIRECTORY.md 20 | git commit -am "updating DIRECTORY.md" || true 21 | git push --force origin HEAD:$GITHUB_REF || true 22 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | pre-commit: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/cache@v2 11 | with: 12 | path: | 13 | ~/.cache/pre-commit 14 | ~/.cache/pip 15 | key: ${{ runner.os }}-pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} 16 | - uses: actions/setup-python@v2 17 | - name: Install pre-commit 18 | run: | 19 | python -m pip install --upgrade pip 20 | python -m pip install --upgrade pre-commit 21 | - run: pre-commit run --verbose --all-files --show-diff-on-failure 22 | -------------------------------------------------------------------------------- /.github/workflows/project_euler.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | # only check if a file is changed within the project_euler directory and related files 4 | paths: 5 | - 'project_euler/**' 6 | - '.github/workflows/project_euler.yml' 7 | - 'scripts/validate_solutions.py' 8 | 9 | name: 'Project Euler' 10 | 11 | jobs: 12 | project-euler: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: actions/setup-python@v2 17 | - name: Install pytest and pytest-cov 18 | run: | 19 | python -m pip install --upgrade pip 20 | python -m pip install --upgrade pytest pytest-cov 21 | - run: pytest --doctest-modules --cov-report=term-missing:skip-covered --cov=project_euler/ project_euler/ 22 | validate-solutions: 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v2 26 | - uses: actions/setup-python@v2 27 | - name: Install pytest 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install --upgrade pytest 31 | - run: pytest scripts/validate_solutions.py 32 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: pip3 install -r ./requirements.txt 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 The Algorithms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /arithmetic_analysis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/arithmetic_analysis/__init__.py -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/2D_problems.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/arithmetic_analysis/image_data/2D_problems.jpg -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/2D_problems_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/arithmetic_analysis/image_data/2D_problems_1.jpg -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/arithmetic_analysis/image_data/__init__.py -------------------------------------------------------------------------------- /arithmetic_analysis/lu_decomposition.py: -------------------------------------------------------------------------------- 1 | """Lower-Upper (LU) Decomposition.""" 2 | 3 | # lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition 4 | import numpy 5 | 6 | 7 | def LUDecompose(table): 8 | # Table that contains our data 9 | # Table has to be a square array so we need to check first 10 | rows, columns = numpy.shape(table) 11 | L = numpy.zeros((rows, columns)) 12 | U = numpy.zeros((rows, columns)) 13 | if rows != columns: 14 | return [] 15 | for i in range(columns): 16 | for j in range(i): 17 | sum = 0 18 | for k in range(j): 19 | sum += L[i][k] * U[k][j] 20 | L[i][j] = (table[i][j] - sum) / U[j][j] 21 | L[i][i] = 1 22 | for j in range(i, columns): 23 | sum1 = 0 24 | for k in range(i): 25 | sum1 += L[i][k] * U[k][j] 26 | U[i][j] = table[i][j] - sum1 27 | return L, U 28 | 29 | 30 | if __name__ == "__main__": 31 | matrix = numpy.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]]) 32 | L, U = LUDecompose(matrix) 33 | print(L) 34 | print(U) 35 | -------------------------------------------------------------------------------- /arithmetic_analysis/secant_method.py: -------------------------------------------------------------------------------- 1 | # Implementing Secant method in Python 2 | # Author: dimgrichr 3 | 4 | 5 | from math import exp 6 | 7 | 8 | def f(x): 9 | """ 10 | >>> f(5) 11 | 39.98652410600183 12 | """ 13 | return 8 * x - 2 * exp(-x) 14 | 15 | 16 | def SecantMethod(lower_bound, upper_bound, repeats): 17 | """ 18 | >>> SecantMethod(1, 3, 2) 19 | 0.2139409276214589 20 | """ 21 | x0 = lower_bound 22 | x1 = upper_bound 23 | for i in range(0, repeats): 24 | x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) 25 | return x1 26 | 27 | 28 | print(f"The solution is: {SecantMethod(1, 3, 2)}") 29 | -------------------------------------------------------------------------------- /backtracking/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/backtracking/__init__.py -------------------------------------------------------------------------------- /backtracking/all_combinations.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this problem, we want to determine all possible combinations of k 3 | numbers out of 1 ... n. We use backtracking to solve this problem. 4 | Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))) 5 | """ 6 | 7 | 8 | def generate_all_combinations(n: int, k: int) -> [[int]]: 9 | """ 10 | >>> generate_all_combinations(n=4, k=2) 11 | [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 12 | """ 13 | 14 | result = [] 15 | create_all_state(1, n, k, [], result) 16 | return result 17 | 18 | 19 | def create_all_state(increment, total_number, level, current_list, total_list): 20 | if level == 0: 21 | total_list.append(current_list[:]) 22 | return 23 | 24 | for i in range(increment, total_number - level + 2): 25 | current_list.append(i) 26 | create_all_state(i + 1, total_number, level - 1, current_list, total_list) 27 | current_list.pop() 28 | 29 | 30 | def print_all_state(total_list): 31 | for i in total_list: 32 | print(*i) 33 | 34 | 35 | if __name__ == "__main__": 36 | n = 4 37 | k = 2 38 | total_list = generate_all_combinations(n, k) 39 | print_all_state(total_list) 40 | -------------------------------------------------------------------------------- /bit_manipulation/README.md: -------------------------------------------------------------------------------- 1 | https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations 2 | https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations 3 | https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types 4 | 5 | https://wiki.python.org/moin/BitManipulation 6 | https://wiki.python.org/moin/BitwiseOperators 7 | https://www.tutorialspoint.com/python3/bitwise_operators_example.htm 8 | -------------------------------------------------------------------------------- /bit_manipulation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/bit_manipulation/__init__.py -------------------------------------------------------------------------------- /blockchain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/blockchain/__init__.py -------------------------------------------------------------------------------- /boolean_algebra/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/boolean_algebra/__init__.py -------------------------------------------------------------------------------- /cellular_automata/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Automata 2 | 3 | * https://en.wikipedia.org/wiki/Cellular_automaton 4 | * https://mathworld.wolfram.com/ElementaryCellularAutomaton.html 5 | -------------------------------------------------------------------------------- /cellular_automata/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/cellular_automata/__init__.py -------------------------------------------------------------------------------- /ciphers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/ciphers/__init__.py -------------------------------------------------------------------------------- /ciphers/a1z26.py: -------------------------------------------------------------------------------- 1 | """ 2 | Convert a string of characters to a sequence of numbers 3 | corresponding to the character's position in the alphabet. 4 | 5 | https://www.dcode.fr/letter-number-cipher 6 | http://bestcodes.weebly.com/a1z26.html 7 | """ 8 | 9 | 10 | def encode(plain: str) -> list: 11 | """ 12 | >>> encode("myname") 13 | [13, 25, 14, 1, 13, 5] 14 | """ 15 | return [ord(elem) - 96 for elem in plain] 16 | 17 | 18 | def decode(encoded: list) -> str: 19 | """ 20 | >>> decode([13, 25, 14, 1, 13, 5]) 21 | 'myname' 22 | """ 23 | return "".join(chr(elem + 96) for elem in encoded) 24 | 25 | 26 | def main(): 27 | encoded = encode(input("->").strip().lower()) 28 | print("Encoded: ", encoded) 29 | print("Decoded:", decode(encoded)) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /ciphers/base16.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def encode_to_b16(inp: str) -> bytes: 5 | """ 6 | Encodes a given utf-8 string into base-16. 7 | >>> encode_to_b16('Hello World!') 8 | b'48656C6C6F20576F726C6421' 9 | >>> encode_to_b16('HELLO WORLD!') 10 | b'48454C4C4F20574F524C4421' 11 | >>> encode_to_b16('') 12 | b'' 13 | """ 14 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 15 | b16encoded = base64.b16encode(encoded) # b16encoded the encoded string 16 | return b16encoded 17 | 18 | 19 | if __name__ == "__main__": 20 | import doctest 21 | 22 | doctest.testmod() 23 | -------------------------------------------------------------------------------- /ciphers/base32.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def main(): 5 | inp = input("->") 6 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 7 | b32encoded = base64.b32encode(encoded) # b32encoded the encoded string 8 | print(b32encoded) 9 | print(base64.b32decode(b32encoded).decode("utf-8")) # decoded it 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /ciphers/base85.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def main(): 5 | inp = input("->") 6 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 7 | a85encoded = base64.a85encode(encoded) # a85encoded the encoded string 8 | print(a85encoded) 9 | print(base64.a85decode(a85encoded).decode("utf-8")) # decoded it 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /ciphers/cryptomath_module.py: -------------------------------------------------------------------------------- 1 | def gcd(a: int, b: int) -> int: 2 | while a != 0: 3 | a, b = b % a, a 4 | return b 5 | 6 | 7 | def findModInverse(a: int, m: int) -> int: 8 | if gcd(a, m) != 1: 9 | return None 10 | u1, u2, u3 = 1, 0, a 11 | v1, v2, v3 = 0, 1, m 12 | while v3 != 0: 13 | q = u3 // v3 14 | v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 15 | return u1 % m 16 | -------------------------------------------------------------------------------- /ciphers/diffie.py: -------------------------------------------------------------------------------- 1 | def find_primitive(n: int) -> int: 2 | for r in range(1, n): 3 | li = [] 4 | for x in range(n - 1): 5 | val = pow(r, x, n) 6 | if val in li: 7 | break 8 | li.append(val) 9 | else: 10 | return r 11 | 12 | 13 | if __name__ == "__main__": 14 | q = int(input("Enter a prime number q: ")) 15 | a = find_primitive(q) 16 | a_private = int(input("Enter private key of A: ")) 17 | a_public = pow(a, a_private, q) 18 | b_private = int(input("Enter private key of B: ")) 19 | b_public = pow(a, b_private, q) 20 | 21 | a_secret = pow(b_public, a_private, q) 22 | b_secret = pow(a_public, b_private, q) 23 | 24 | print("The key value generated by A is: ", a_secret) 25 | print("The key value generated by B is: ", b_secret) 26 | -------------------------------------------------------------------------------- /ciphers/onepad_cipher.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class Onepad: 5 | def encrypt(self, text: str) -> ([str], [int]): 6 | """Function to encrypt text using pseudo-random numbers""" 7 | plain = [ord(i) for i in text] 8 | key = [] 9 | cipher = [] 10 | for i in plain: 11 | k = random.randint(1, 300) 12 | c = (i + k) * k 13 | cipher.append(c) 14 | key.append(k) 15 | return cipher, key 16 | 17 | def decrypt(self, cipher: [str], key: [int]) -> str: 18 | """Function to decrypt text using pseudo-random numbers.""" 19 | plain = [] 20 | for i in range(len(key)): 21 | p = int((cipher[i] - (key[i]) ** 2) / key[i]) 22 | plain.append(chr(p)) 23 | plain = "".join([i for i in plain]) 24 | return plain 25 | 26 | 27 | if __name__ == "__main__": 28 | c, k = Onepad().encrypt("Hello") 29 | print(c, k) 30 | print(Onepad().decrypt(c, k)) 31 | -------------------------------------------------------------------------------- /ciphers/prehistoric_men.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/ciphers/prehistoric_men.txt -------------------------------------------------------------------------------- /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(): 24 | s0 = input("Enter message: ") 25 | 26 | s1 = dencrypt(s0, 13) 27 | print("Encryption:", s1) 28 | 29 | s2 = dencrypt(s1, 13) 30 | print("Decryption: ", s2) 31 | 32 | 33 | if __name__ == "__main__": 34 | import doctest 35 | 36 | doctest.testmod() 37 | main() 38 | -------------------------------------------------------------------------------- /compression/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/__init__.py -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-base.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/PSNR-example-base.png -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-comp-10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/PSNR-example-comp-10.jpg -------------------------------------------------------------------------------- /compression/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/__init__.py -------------------------------------------------------------------------------- /compression/image_data/compressed_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/compressed_image.png -------------------------------------------------------------------------------- /compression/image_data/example_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/example_image.jpg -------------------------------------------------------------------------------- /compression/image_data/example_wikipedia_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/example_wikipedia_image.jpg -------------------------------------------------------------------------------- /compression/image_data/original_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/compression/image_data/original_image.png -------------------------------------------------------------------------------- /computer_vision/README.md: -------------------------------------------------------------------------------- 1 | ### Computer Vision 2 | 3 | Computer vision is a field of computer science that works on enabling computers to see, 4 | identify and process images in the same way that human vision does, and then provide appropriate output. 5 | It is like imparting human intelligence and instincts to a computer. 6 | Image processing and computer vision 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 | 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). 8 | -------------------------------------------------------------------------------- /computer_vision/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/computer_vision/__init__.py -------------------------------------------------------------------------------- /computer_vision/meanthreshold.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | """ 4 | Mean thresholding algorithm for image processing 5 | https://en.wikipedia.org/wiki/Thresholding_(image_processing) 6 | """ 7 | 8 | 9 | def mean_threshold(image: Image) -> Image: 10 | """ 11 | image: is a grayscale PIL image object 12 | """ 13 | height, width = image.size 14 | mean = 0 15 | pixels = image.load() 16 | for i in range(width): 17 | for j in range(height): 18 | pixel = pixels[j, i] 19 | mean += pixel 20 | mean //= width * height 21 | 22 | for j in range(width): 23 | for i in range(height): 24 | pixels[i, j] = 255 if pixels[i, j] > mean else 0 25 | return image 26 | 27 | 28 | if __name__ == "__main__": 29 | image = mean_threshold(Image.open("path_to_image").convert("L")) 30 | image.save("output_image_path") 31 | -------------------------------------------------------------------------------- /conversions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/conversions/__init__.py -------------------------------------------------------------------------------- /conversions/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | def roman_to_int(roman: str) -> int: 2 | """ 3 | LeetCode No. 13 Roman to Integer 4 | Given a roman numeral, convert it to an integer. 5 | Input is guaranteed to be within the range from 1 to 3999. 6 | https://en.wikipedia.org/wiki/Roman_numerals 7 | >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} 8 | >>> all(roman_to_int(key) == value for key, value in tests.items()) 9 | True 10 | """ 11 | vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 12 | total = 0 13 | place = 0 14 | while place < len(roman): 15 | if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): 16 | total += vals[roman[place + 1]] - vals[roman[place]] 17 | place += 2 18 | else: 19 | total += vals[roman[place]] 20 | place += 1 21 | return total 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /data_structures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/__init__.py -------------------------------------------------------------------------------- /data_structures/binary_tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/binary_tree/__init__.py -------------------------------------------------------------------------------- /data_structures/binary_tree/fenwick_tree.py: -------------------------------------------------------------------------------- 1 | class FenwickTree: 2 | def __init__(self, SIZE): # create fenwick tree with size SIZE 3 | self.Size = SIZE 4 | self.ft = [0 for i in range(0, SIZE)] 5 | 6 | def update(self, i, val): # update data (adding) in index i in O(lg N) 7 | while i < self.Size: 8 | self.ft[i] += val 9 | i += i & (-i) 10 | 11 | def query(self, i): # query cumulative data from index 0 to i in O(lg N) 12 | ret = 0 13 | while i > 0: 14 | ret += self.ft[i] 15 | i -= i & (-i) 16 | return ret 17 | 18 | 19 | if __name__ == "__main__": 20 | f = FenwickTree(100) 21 | f.update(1, 20) 22 | f.update(4, 4) 23 | print(f.query(1)) 24 | print(f.query(3)) 25 | print(f.query(4)) 26 | f.update(2, -5) 27 | print(f.query(1)) 28 | print(f.query(3)) 29 | -------------------------------------------------------------------------------- /data_structures/disjoint_set/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/disjoint_set/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/hashing/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/hash_table_with_linked_list.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | from .hash_table import HashTable 4 | 5 | 6 | class HashTableWithLinkedList(HashTable): 7 | def __init__(self, *args, **kwargs): 8 | super().__init__(*args, **kwargs) 9 | 10 | def _set_value(self, key, data): 11 | self.values[key] = deque([]) if self.values[key] is None else self.values[key] 12 | self.values[key].appendleft(data) 13 | self._keys[key] = self.values[key] 14 | 15 | def balanced_factor(self): 16 | return ( 17 | sum([self.charge_factor - len(slot) for slot in self.values]) 18 | / self.size_table 19 | * self.charge_factor 20 | ) 21 | 22 | def _collision_resolution(self, key, data=None): 23 | if not ( 24 | len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 25 | ): 26 | return key 27 | return super()._collision_resolution(key, data) 28 | -------------------------------------------------------------------------------- /data_structures/hashing/number_theory/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/hashing/number_theory/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/number_theory/prime_numbers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | module to operations with prime numbers 4 | """ 5 | 6 | 7 | def check_prime(number): 8 | """ 9 | it's not the best solution 10 | """ 11 | special_non_primes = [0, 1, 2] 12 | if number in special_non_primes[:2]: 13 | return 2 14 | elif number == special_non_primes[-1]: 15 | return 3 16 | 17 | return all([number % i for i in range(2, number)]) 18 | 19 | 20 | def next_prime(value, factor=1, **kwargs): 21 | value = factor * value 22 | first_value_val = value 23 | 24 | while not check_prime(value): 25 | value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1 26 | 27 | if value == first_value_val: 28 | return next_prime(value + 1, **kwargs) 29 | return value 30 | -------------------------------------------------------------------------------- /data_structures/hashing/quadratic_probing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .hash_table import HashTable 4 | 5 | 6 | class QuadraticProbing(HashTable): 7 | """ 8 | Basic Hash Table example with open addressing using Quadratic Probing 9 | """ 10 | 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | 14 | def _collision_resolution(self, key, data=None): 15 | i = 1 16 | new_key = self.hash_function(key + i * i) 17 | 18 | while self.values[new_key] is not None and self.values[new_key] != key: 19 | i += 1 20 | new_key = ( 21 | self.hash_function(key + i * i) 22 | if not self.balanced_factor() >= self.lim_charge 23 | else None 24 | ) 25 | 26 | if new_key is None: 27 | break 28 | 29 | return new_key 30 | -------------------------------------------------------------------------------- /data_structures/heap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/heap/__init__.py -------------------------------------------------------------------------------- /data_structures/linked_list/__init__.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, item, next): 3 | self.item = item 4 | self.next = next 5 | 6 | 7 | class LinkedList: 8 | def __init__(self): 9 | self.head = None 10 | self.size = 0 11 | 12 | def add(self, item): 13 | self.head = Node(item, self.head) 14 | self.size += 1 15 | 16 | def remove(self): 17 | if self.is_empty(): 18 | return None 19 | else: 20 | item = self.head.item 21 | self.head = self.head.next 22 | self.size -= 1 23 | return item 24 | 25 | def is_empty(self): 26 | return self.head is None 27 | 28 | def __len__(self): 29 | """ 30 | >>> linked_list = LinkedList() 31 | >>> len(linked_list) 32 | 0 33 | >>> linked_list.add("a") 34 | >>> len(linked_list) 35 | 1 36 | >>> linked_list.add("b") 37 | >>> len(linked_list) 38 | 2 39 | >>> _ = linked_list.remove() 40 | >>> len(linked_list) 41 | 1 42 | >>> _ = linked_list.remove() 43 | >>> len(linked_list) 44 | 0 45 | """ 46 | return self.size 47 | -------------------------------------------------------------------------------- /data_structures/queue/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/queue/__init__.py -------------------------------------------------------------------------------- /data_structures/stacks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/stacks/__init__.py -------------------------------------------------------------------------------- /data_structures/stacks/balanced_parentheses.py: -------------------------------------------------------------------------------- 1 | from .stack import Stack 2 | 3 | 4 | def balanced_parentheses(parentheses: str) -> bool: 5 | """Use a stack to check if a string of parentheses is balanced. 6 | >>> balanced_parentheses("([]{})") 7 | True 8 | >>> balanced_parentheses("[()]{}{[()()]()}") 9 | True 10 | >>> balanced_parentheses("[(])") 11 | False 12 | >>> balanced_parentheses("1+2*3-4") 13 | True 14 | >>> balanced_parentheses("") 15 | True 16 | """ 17 | stack = Stack() 18 | bracket_pairs = {"(": ")", "[": "]", "{": "}"} 19 | for bracket in parentheses: 20 | if bracket in bracket_pairs: 21 | stack.push(bracket) 22 | elif bracket in (")", "]", "}"): 23 | if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: 24 | return False 25 | return stack.is_empty() 26 | 27 | 28 | if __name__ == "__main__": 29 | from doctest import testmod 30 | 31 | testmod() 32 | 33 | examples = ["((()))", "((())", "(()))"] 34 | print("Balanced parentheses demonstration:\n") 35 | for example in examples: 36 | not_str = "" if balanced_parentheses(example) else "not " 37 | print(f"{example} is {not_str}balanced") 38 | -------------------------------------------------------------------------------- /data_structures/trie/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/data_structures/trie/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/change_brightness.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | 4 | def change_brightness(img: Image, level: float) -> Image: 5 | """ 6 | Change the brightness of a PIL Image to a given level. 7 | """ 8 | 9 | def brightness(c: int) -> float: 10 | """ 11 | Fundamental Transformation/Operation that'll be performed on 12 | every bit. 13 | """ 14 | return 128 + level + (c - 128) 15 | 16 | if not -255.0 <= level <= 255.0: 17 | raise ValueError("level must be between -255.0 (black) and 255.0 (white)") 18 | return img.point(brightness) 19 | 20 | 21 | if __name__ == "__main__": 22 | # Load image 23 | with Image.open("image_data/lena.jpg") as img: 24 | # Change brightness to 100 25 | brigt_img = change_brightness(img, 100) 26 | brigt_img.save("image_data/lena_brightness.png", format="png") 27 | -------------------------------------------------------------------------------- /digital_image_processing/change_contrast.py: -------------------------------------------------------------------------------- 1 | """ 2 | Changing contrast with PIL 3 | 4 | This algorithm is used in 5 | https://noivce.pythonanywhere.com/ Python web app. 6 | 7 | python/black: True 8 | flake8 : True 9 | """ 10 | 11 | from PIL import Image 12 | 13 | 14 | def change_contrast(img: Image, level: int) -> Image: 15 | """ 16 | Function to change contrast 17 | """ 18 | factor = (259 * (level + 255)) / (255 * (259 - level)) 19 | 20 | def contrast(c: int) -> int: 21 | """ 22 | Fundamental Transformation/Operation that'll be performed on 23 | every bit. 24 | """ 25 | return int(128 + factor * (c - 128)) 26 | 27 | return img.point(contrast) 28 | 29 | 30 | if __name__ == "__main__": 31 | # Load image 32 | with Image.open("image_data/lena.jpg") as img: 33 | # Change contrast to 170 34 | cont_img = change_contrast(img, 170) 35 | cont_img.save("image_data/lena_high_contrast.png", format="png") 36 | -------------------------------------------------------------------------------- /digital_image_processing/convert_to_negative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implemented an algorithm using opencv to convert a colored image into its negative 3 | """ 4 | from cv2 import destroyAllWindows, imread, imshow, waitKey 5 | 6 | 7 | def convert_to_negative(img): 8 | # getting number of pixels in the image 9 | pixel_h, pixel_v = img.shape[0], img.shape[1] 10 | 11 | # converting each pixel's color to its negative 12 | for i in range(pixel_h): 13 | for j in range(pixel_v): 14 | img[i][j] = [255, 255, 255] - img[i][j] 15 | 16 | return img 17 | 18 | 19 | if __name__ == "__main__": 20 | # read original image 21 | img = imread("image_data/lena.jpg", 1) 22 | 23 | # convert to its negative 24 | neg = convert_to_negative(img) 25 | 26 | # show result image 27 | imshow("negative of original image", img) 28 | waitKey(0) 29 | destroyAllWindows() 30 | -------------------------------------------------------------------------------- /digital_image_processing/dithering/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/dithering/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/edge_detection/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/edge_detection/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/filters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/filters/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/histogram_equalization/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/histogram_equalization/image_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/histogram_equalization/image_data/input.jpg -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/histogram_equalization/output_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/histogram_equalization/output_data/output.jpg -------------------------------------------------------------------------------- /digital_image_processing/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/image_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/image_data/lena.jpg -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/image_data/lena_small.jpg -------------------------------------------------------------------------------- /digital_image_processing/resize/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/resize/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/rotation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/digital_image_processing/rotation/__init__.py -------------------------------------------------------------------------------- /divide_and_conquer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/divide_and_conquer/__init__.py -------------------------------------------------------------------------------- /divide_and_conquer/power.py: -------------------------------------------------------------------------------- 1 | def actual_power(a: int, b: int): 2 | """ 3 | Function using divide and conquer to calculate a^b. 4 | It only works for integer a,b. 5 | """ 6 | if b == 0: 7 | return 1 8 | if (b % 2) == 0: 9 | return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) 10 | else: 11 | return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) 12 | 13 | 14 | def power(a: int, b: int) -> float: 15 | """ 16 | >>> power(4,6) 17 | 4096 18 | >>> power(2,3) 19 | 8 20 | >>> power(-2,3) 21 | -8 22 | >>> power(2,-3) 23 | 0.125 24 | >>> power(-2,-3) 25 | -0.125 26 | """ 27 | if b < 0: 28 | return 1 / actual_power(a, b) 29 | return actual_power(a, b) 30 | 31 | 32 | if __name__ == "__main__": 33 | print(power(-2, -3)) 34 | -------------------------------------------------------------------------------- /dynamic_programming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/dynamic_programming/__init__.py -------------------------------------------------------------------------------- /dynamic_programming/abbreviation.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/abbr/problem 3 | You can perform the following operation on some string, : 4 | 5 | 1. Capitalize zero or more of 's lowercase letters at some index i 6 | (i.e., make them uppercase). 7 | 2. Delete all of the remaining lowercase letters in . 8 | 9 | Example: 10 | a=daBcd and b="ABC" 11 | daBcd -> capitalize a and c(dABCd) -> remove d (ABC) 12 | """ 13 | 14 | 15 | def abbr(a: str, b: str) -> bool: 16 | """ 17 | >>> abbr("daBcd", "ABC") 18 | True 19 | >>> abbr("dBcd", "ABC") 20 | False 21 | """ 22 | n = len(a) 23 | m = len(b) 24 | dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] 25 | dp[0][0] = True 26 | for i in range(n): 27 | for j in range(m + 1): 28 | if dp[i][j]: 29 | if j < m and a[i].upper() == b[j]: 30 | dp[i + 1][j + 1] = True 31 | if a[i].islower(): 32 | dp[i + 1][j] = True 33 | return dp[n][m] 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | -------------------------------------------------------------------------------- /dynamic_programming/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | def climb_stairs(n: int) -> int: 5 | """ 6 | LeetCdoe No.70: Climbing Stairs 7 | Distinct ways to climb a n step staircase where 8 | each time you can either climb 1 or 2 steps. 9 | 10 | Args: 11 | n: number of steps of staircase 12 | 13 | Returns: 14 | Distinct ways to climb a n step staircase 15 | 16 | Raises: 17 | AssertionError: n not positive integer 18 | 19 | >>> climb_stairs(3) 20 | 3 21 | >>> climb_stairs(1) 22 | 1 23 | >>> climb_stairs(-7) # doctest: +ELLIPSIS 24 | Traceback (most recent call last): 25 | ... 26 | AssertionError: n needs to be positive integer, your input -7 27 | """ 28 | fmt = "n needs to be positive integer, your input {}" 29 | assert isinstance(n, int) and n > 0, fmt.format(n) 30 | if n == 1: 31 | return 1 32 | dp = [0] * (n + 1) 33 | dp[0], dp[1] = (1, 1) 34 | for i in range(2, n + 1): 35 | dp[i] = dp[i - 1] + dp[i - 2] 36 | return dp[n] 37 | 38 | 39 | if __name__ == "__main__": 40 | import doctest 41 | 42 | doctest.testmod() 43 | -------------------------------------------------------------------------------- /dynamic_programming/factorial.py: -------------------------------------------------------------------------------- 1 | # Factorial of a number using memoization 2 | 3 | from functools import lru_cache 4 | 5 | 6 | @lru_cache 7 | def factorial(num: int) -> int: 8 | """ 9 | >>> factorial(7) 10 | 5040 11 | >>> factorial(-1) 12 | Traceback (most recent call last): 13 | ... 14 | ValueError: Number should not be negative. 15 | >>> [factorial(i) for i in range(10)] 16 | [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] 17 | """ 18 | if num < 0: 19 | raise ValueError("Number should not be negative.") 20 | 21 | return 1 if num in (0, 1) else num * factorial(num - 1) 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /dynamic_programming/fast_fibonacci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | This program calculates the nth Fibonacci number in O(log(n)). 5 | It's possible to calculate F(1_000_000) in less than a second. 6 | """ 7 | from __future__ import annotations 8 | 9 | import sys 10 | 11 | 12 | def fibonacci(n: int) -> int: 13 | """ 14 | return F(n) 15 | >>> [fibonacci(i) for i in range(13)] 16 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] 17 | """ 18 | if n < 0: 19 | raise ValueError("Negative arguments are not supported") 20 | return _fib(n)[0] 21 | 22 | 23 | # returns (F(n), F(n-1)) 24 | def _fib(n: int) -> tuple[int, int]: 25 | if n == 0: # (F(0), F(1)) 26 | return (0, 1) 27 | 28 | # F(2n) = F(n)[2F(n+1) − F(n)] 29 | # F(2n+1) = F(n+1)^2+F(n)^2 30 | a, b = _fib(n // 2) 31 | c = a * (b * 2 - a) 32 | d = a * a + b * b 33 | return (d, c + d) if n % 2 else (c, d) 34 | 35 | 36 | if __name__ == "__main__": 37 | n = int(sys.argv[1]) 38 | print(f"fibonacci({n}) is {fibonacci(n)}") 39 | -------------------------------------------------------------------------------- /dynamic_programming/fractional_knapsack.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from itertools import accumulate 3 | 4 | 5 | def fracKnapsack(vl, wt, W, n): 6 | """ 7 | >>> fracKnapsack([60, 100, 120], [10, 20, 30], 50, 3) 8 | 240.0 9 | """ 10 | 11 | r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True)) 12 | vl, wt = [i[0] for i in r], [i[1] for i in r] 13 | acc = list(accumulate(wt)) 14 | k = bisect(acc, W) 15 | return ( 16 | 0 17 | if k == 0 18 | else sum(vl[:k]) + (W - acc[k - 1]) * (vl[k]) / (wt[k]) 19 | if k != n 20 | else sum(vl[:k]) 21 | ) 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /dynamic_programming/integer_partition.py: -------------------------------------------------------------------------------- 1 | """ 2 | The number of partitions of a number n into at least k parts equals the number of 3 | partitions into exactly k parts plus the number of partitions into at least k-1 parts. 4 | Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k 5 | into k parts. These two facts together are used for this algorithm. 6 | """ 7 | 8 | 9 | def partition(m): 10 | memo = [[0 for _ in range(m)] for _ in range(m + 1)] 11 | for i in range(m + 1): 12 | memo[i][0] = 1 13 | 14 | for n in range(m + 1): 15 | for k in range(1, m): 16 | memo[n][k] += memo[n][k - 1] 17 | if n - k > 0: 18 | memo[n][k] += memo[n - k - 1][k] 19 | 20 | return memo[m][m - 1] 21 | 22 | 23 | if __name__ == "__main__": 24 | import sys 25 | 26 | if len(sys.argv) == 1: 27 | try: 28 | n = int(input("Enter a number: ").strip()) 29 | print(partition(n)) 30 | except ValueError: 31 | print("Please enter a number.") 32 | else: 33 | try: 34 | n = int(sys.argv[1]) 35 | print(partition(n)) 36 | except ValueError: 37 | print("Please pass a number.") 38 | -------------------------------------------------------------------------------- /dynamic_programming/longest_sub_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author : Yvonne 3 | 4 | This is a pure Python implementation of Dynamic Programming solution to the 5 | longest_sub_array problem. 6 | 7 | The problem is : 8 | Given an array, to find the longest and continuous sub array and get the max sum of the 9 | sub array in the given array. 10 | """ 11 | 12 | 13 | class SubArray: 14 | def __init__(self, arr): 15 | # we need a list not a string, so do something to change the type 16 | self.array = arr.split(",") 17 | print(("the input array is:", self.array)) 18 | 19 | def solve_sub_array(self): 20 | rear = [int(self.array[0])] * len(self.array) 21 | sum_value = [int(self.array[0])] * len(self.array) 22 | for i in range(1, len(self.array)): 23 | sum_value[i] = max( 24 | int(self.array[i]) + sum_value[i - 1], int(self.array[i]) 25 | ) 26 | rear[i] = max(sum_value[i], rear[i - 1]) 27 | return rear[len(self.array) - 1] 28 | 29 | 30 | if __name__ == "__main__": 31 | whole_array = input("please input some numbers:") 32 | array = SubArray(whole_array) 33 | re = array.solve_sub_array() 34 | print(("the results is:", re)) 35 | -------------------------------------------------------------------------------- /dynamic_programming/max_non_adjacent_sum.py: -------------------------------------------------------------------------------- 1 | # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo 2 | 3 | from __future__ import annotations 4 | 5 | 6 | def maximum_non_adjacent_sum(nums: list[int]) -> int: 7 | """ 8 | Find the maximum non-adjacent sum of the integers in the nums input list 9 | 10 | >>> print(maximum_non_adjacent_sum([1, 2, 3])) 11 | 4 12 | >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6]) 13 | 18 14 | >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6]) 15 | 0 16 | >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6]) 17 | 500 18 | """ 19 | if not nums: 20 | return 0 21 | max_including = nums[0] 22 | max_excluding = 0 23 | for num in nums[1:]: 24 | max_including, max_excluding = ( 25 | max_excluding + num, 26 | max(max_including, max_excluding), 27 | ) 28 | return max(max_excluding, max_including) 29 | 30 | 31 | if __name__ == "__main__": 32 | import doctest 33 | 34 | doctest.testmod() 35 | -------------------------------------------------------------------------------- /dynamic_programming/max_sum_contiguous_subsequence.py: -------------------------------------------------------------------------------- 1 | def max_subarray_sum(nums: list) -> int: 2 | """ 3 | >>> max_subarray_sum([6 , 9, -1, 3, -7, -5, 10]) 4 | 17 5 | """ 6 | if not nums: 7 | return 0 8 | n = len(nums) 9 | 10 | res, s, s_pre = nums[0], nums[0], nums[0] 11 | for i in range(1, n): 12 | s = max(nums[i], s_pre + nums[i]) 13 | s_pre = s 14 | res = max(res, s) 15 | return res 16 | 17 | 18 | if __name__ == "__main__": 19 | nums = [6, 9, -1, 3, -7, -5, 10] 20 | print(max_subarray_sum(nums)) 21 | -------------------------------------------------------------------------------- /dynamic_programming/minimum_cost_path.py: -------------------------------------------------------------------------------- 1 | # Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU 2 | 3 | from __future__ import annotations 4 | 5 | 6 | def minimum_cost_path(matrix: list[list[int]]) -> int: 7 | """ 8 | Find the minimum cost traced by all possible paths from top left to bottom right in 9 | a given matrix 10 | 11 | >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 12 | 6 13 | 14 | >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 15 | 7 16 | """ 17 | 18 | # preprocessing the first row 19 | for i in range(1, len(matrix[0])): 20 | matrix[0][i] += matrix[0][i - 1] 21 | 22 | # preprocessing the first column 23 | for i in range(1, len(matrix)): 24 | matrix[i][0] += matrix[i - 1][0] 25 | 26 | # updating the path cost for current position 27 | for i in range(1, len(matrix)): 28 | for j in range(1, len(matrix[0])): 29 | matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) 30 | 31 | return matrix[-1][-1] 32 | 33 | 34 | if __name__ == "__main__": 35 | import doctest 36 | 37 | doctest.testmod() 38 | -------------------------------------------------------------------------------- /dynamic_programming/minimum_partition.py: -------------------------------------------------------------------------------- 1 | """ 2 | Partition a set into two subsets such that the difference of subset sums is minimum 3 | """ 4 | 5 | 6 | def findMin(arr): 7 | n = len(arr) 8 | s = sum(arr) 9 | 10 | dp = [[False for x in range(s + 1)] for y in range(n + 1)] 11 | 12 | for i in range(1, n + 1): 13 | dp[i][0] = True 14 | 15 | for i in range(1, s + 1): 16 | dp[0][i] = False 17 | 18 | for i in range(1, n + 1): 19 | for j in range(1, s + 1): 20 | dp[i][j] = dp[i][j - 1] 21 | 22 | if arr[i - 1] <= j: 23 | dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]] 24 | 25 | for j in range(int(s / 2), -1, -1): 26 | if dp[n][j] is True: 27 | diff = s - 2 * j 28 | break 29 | 30 | return diff 31 | -------------------------------------------------------------------------------- /file_transfer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/file_transfer/__init__.py -------------------------------------------------------------------------------- /file_transfer/mytext.txt: -------------------------------------------------------------------------------- 1 | Hello 2 | This is sample data 3 | «küßî» 4 | “ЌύБЇ” 5 | 😀😉 6 | 😋 7 | -------------------------------------------------------------------------------- /file_transfer/receive_file.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | import socket # Import socket module 3 | 4 | sock = socket.socket() # Create a socket object 5 | host = socket.gethostname() # Get local machine name 6 | port = 12312 7 | 8 | sock.connect((host, port)) 9 | sock.send(b"Hello server!") 10 | 11 | with open("Received_file", "wb") as out_file: 12 | print("File opened") 13 | print("Receiving data...") 14 | while True: 15 | data = sock.recv(1024) 16 | print(f"data={data}") 17 | if not data: 18 | break 19 | out_file.write(data) # Write data to a file 20 | 21 | print("Successfully got the file") 22 | sock.close() 23 | print("Connection closed") 24 | -------------------------------------------------------------------------------- /file_transfer/send_file.py: -------------------------------------------------------------------------------- 1 | def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: 2 | import socket 3 | 4 | port = 12312 # Reserve a port for your service. 5 | sock = socket.socket() # Create a socket object 6 | host = socket.gethostname() # Get local machine name 7 | sock.bind((host, port)) # Bind to the port 8 | sock.listen(5) # Now wait for client connection. 9 | 10 | print("Server listening....") 11 | 12 | while True: 13 | conn, addr = sock.accept() # Establish connection with client. 14 | print(f"Got connection from {addr}") 15 | data = conn.recv(1024) 16 | print(f"Server received {data}") 17 | 18 | with open(filename, "rb") as in_file: 19 | data = in_file.read(1024) 20 | while data: 21 | conn.send(data) 22 | print(f"Sent {data!r}") 23 | data = in_file.read(1024) 24 | 25 | print("Done sending") 26 | conn.close() 27 | if testing: # Allow the test to complete 28 | break 29 | 30 | sock.shutdown(1) 31 | sock.close() 32 | 33 | 34 | if __name__ == "__main__": 35 | send_file() 36 | -------------------------------------------------------------------------------- /file_transfer/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/file_transfer/tests/__init__.py -------------------------------------------------------------------------------- /file_transfer/tests/test_send_file.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import Mock, patch 2 | 3 | from file_transfer.send_file import send_file 4 | 5 | 6 | @patch("socket.socket") 7 | @patch("builtins.open") 8 | def test_send_file_running_as_expected(file, sock): 9 | # ===== initialization ===== 10 | conn = Mock() 11 | sock.return_value.accept.return_value = conn, Mock() 12 | f = iter([1, None]) 13 | file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) 14 | 15 | # ===== invoke ===== 16 | send_file(filename="mytext.txt", testing=True) 17 | 18 | # ===== ensurance ===== 19 | sock.assert_called_once() 20 | sock.return_value.bind.assert_called_once() 21 | sock.return_value.listen.assert_called_once() 22 | sock.return_value.accept.assert_called_once() 23 | conn.recv.assert_called_once() 24 | 25 | file.return_value.__enter__.assert_called_once() 26 | file.return_value.__enter__.return_value.read.assert_called() 27 | 28 | conn.send.assert_called_once() 29 | conn.close.assert_called_once() 30 | sock.return_value.shutdown.assert_called_once() 31 | sock.return_value.close.assert_called_once() 32 | -------------------------------------------------------------------------------- /fuzzy_logic/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/fuzzy_logic/__init__.py -------------------------------------------------------------------------------- /genetic_algorithm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/genetic_algorithm/__init__.py -------------------------------------------------------------------------------- /geodesy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/geodesy/__init__.py -------------------------------------------------------------------------------- /graphics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/graphics/__init__.py -------------------------------------------------------------------------------- /graphs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/graphs/__init__.py -------------------------------------------------------------------------------- /graphs/check_bipartite_graph_dfs.py: -------------------------------------------------------------------------------- 1 | # Check whether Graph is Bipartite or Not using DFS 2 | 3 | 4 | # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, 5 | # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex 6 | # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, 7 | # or u belongs to V and v to U. We can also say that there is no edge that connects 8 | # vertices of same set. 9 | def check_bipartite_dfs(graph): 10 | visited = [False] * len(graph) 11 | color = [-1] * len(graph) 12 | 13 | def dfs(v, c): 14 | visited[v] = True 15 | color[v] = c 16 | for u in graph[v]: 17 | if not visited[u]: 18 | dfs(u, 1 - c) 19 | 20 | for i in range(len(graph)): 21 | if not visited[i]: 22 | dfs(i, 0) 23 | 24 | for i in range(len(graph)): 25 | for j in graph[i]: 26 | if color[i] == color[j]: 27 | return False 28 | 29 | return True 30 | 31 | 32 | # Adjacency list of graph 33 | graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} 34 | print(check_bipartite_dfs(graph)) 35 | -------------------------------------------------------------------------------- /graphs/finding_bridges.py: -------------------------------------------------------------------------------- 1 | # Finding Bridges in Undirected Graph 2 | def computeBridges(graph): 3 | id = 0 4 | n = len(graph) # No of vertices in graph 5 | low = [0] * n 6 | visited = [False] * n 7 | 8 | def dfs(at, parent, bridges, id): 9 | visited[at] = True 10 | low[at] = id 11 | id += 1 12 | for to in graph[at]: 13 | if to == parent: 14 | pass 15 | elif not visited[to]: 16 | dfs(to, at, bridges, id) 17 | low[at] = min(low[at], low[to]) 18 | if at < low[to]: 19 | bridges.append([at, to]) 20 | else: 21 | # This edge is a back edge and cannot be a bridge 22 | low[at] = min(low[at], to) 23 | 24 | bridges = [] 25 | for i in range(n): 26 | if not visited[i]: 27 | dfs(i, -1, bridges, id) 28 | print(bridges) 29 | 30 | 31 | graph = { 32 | 0: [1, 2], 33 | 1: [0, 2], 34 | 2: [0, 1, 3, 5], 35 | 3: [2, 4], 36 | 4: [3], 37 | 5: [2, 6, 8], 38 | 6: [5, 7], 39 | 7: [6, 8], 40 | 8: [5, 7], 41 | } 42 | computeBridges(graph) 43 | -------------------------------------------------------------------------------- /graphs/g_topological_sort.py: -------------------------------------------------------------------------------- 1 | # Author: Phyllipe Bezerra (https://github.com/pmba) 2 | 3 | clothes = { 4 | 0: "underwear", 5 | 1: "pants", 6 | 2: "belt", 7 | 3: "suit", 8 | 4: "shoe", 9 | 5: "socks", 10 | 6: "shirt", 11 | 7: "tie", 12 | 8: "watch", 13 | } 14 | 15 | graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] 16 | 17 | visited = [0 for x in range(len(graph))] 18 | stack = [] 19 | 20 | 21 | def print_stack(stack, clothes): 22 | order = 1 23 | while stack: 24 | current_clothing = stack.pop() 25 | print(order, clothes[current_clothing]) 26 | order += 1 27 | 28 | 29 | def depth_first_search(u, visited, graph): 30 | visited[u] = 1 31 | for v in graph[u]: 32 | if not visited[v]: 33 | depth_first_search(v, visited, graph) 34 | 35 | stack.append(u) 36 | 37 | 38 | def topological_sort(graph, visited): 39 | for v in range(len(graph)): 40 | if not visited[v]: 41 | depth_first_search(v, visited, graph) 42 | 43 | 44 | if __name__ == "__main__": 45 | topological_sort(graph, visited) 46 | print(stack) 47 | print_stack(stack, clothes) 48 | -------------------------------------------------------------------------------- /graphs/graph_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Author: OMKAR PATHAK 4 | 5 | # We can use Python's dictionary for constructing the graph. 6 | 7 | 8 | class AdjacencyList: 9 | def __init__(self): 10 | self.adj_list = {} 11 | 12 | def add_edge(self, from_vertex: int, to_vertex: int) -> None: 13 | # check if vertex is already present 14 | if from_vertex in self.adj_list: 15 | self.adj_list[from_vertex].append(to_vertex) 16 | else: 17 | self.adj_list[from_vertex] = [to_vertex] 18 | 19 | def print_list(self) -> None: 20 | for i in self.adj_list: 21 | print((i, "->", " -> ".join([str(j) for j in self.adj_list[i]]))) 22 | 23 | 24 | if __name__ == "__main__": 25 | al = AdjacencyList() 26 | al.add_edge(0, 1) 27 | al.add_edge(0, 4) 28 | al.add_edge(4, 1) 29 | al.add_edge(4, 3) 30 | al.add_edge(1, 0) 31 | al.add_edge(1, 4) 32 | al.add_edge(1, 3) 33 | al.add_edge(1, 2) 34 | al.add_edge(2, 3) 35 | al.add_edge(3, 4) 36 | 37 | al.print_list() 38 | 39 | # OUTPUT: 40 | # 0 -> 1 -> 4 41 | # 1 -> 0 -> 4 -> 3 -> 2 42 | # 2 -> 3 43 | # 3 -> 4 44 | # 4 -> 1 -> 3 45 | -------------------------------------------------------------------------------- /graphs/graph_matrix.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertex): 3 | self.vertex = vertex 4 | self.graph = [[0] * vertex for i in range(vertex)] 5 | 6 | def add_edge(self, u, v): 7 | self.graph[u - 1][v - 1] = 1 8 | self.graph[v - 1][u - 1] = 1 9 | 10 | def show(self): 11 | 12 | for i in self.graph: 13 | for j in i: 14 | print(j, end=" ") 15 | print(" ") 16 | 17 | 18 | g = Graph(100) 19 | 20 | g.add_edge(1, 4) 21 | g.add_edge(4, 2) 22 | g.add_edge(4, 5) 23 | g.add_edge(2, 5) 24 | g.add_edge(5, 3) 25 | g.show() 26 | -------------------------------------------------------------------------------- /graphs/kahns_algorithm_long.py: -------------------------------------------------------------------------------- 1 | # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm 2 | def longestDistance(graph): 3 | indegree = [0] * len(graph) 4 | queue = [] 5 | longDist = [1] * len(graph) 6 | 7 | for key, values in graph.items(): 8 | for i in values: 9 | indegree[i] += 1 10 | 11 | for i in range(len(indegree)): 12 | if indegree[i] == 0: 13 | queue.append(i) 14 | 15 | while queue: 16 | vertex = queue.pop(0) 17 | for x in graph[vertex]: 18 | indegree[x] -= 1 19 | 20 | if longDist[vertex] + 1 > longDist[x]: 21 | longDist[x] = longDist[vertex] + 1 22 | 23 | if indegree[x] == 0: 24 | queue.append(x) 25 | 26 | print(max(longDist)) 27 | 28 | 29 | # Adjacency list of Graph 30 | graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} 31 | longestDistance(graph) 32 | -------------------------------------------------------------------------------- /graphs/kahns_algorithm_topo.py: -------------------------------------------------------------------------------- 1 | def topologicalSort(graph): 2 | """ 3 | Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph 4 | using BFS 5 | """ 6 | indegree = [0] * len(graph) 7 | queue = [] 8 | topo = [] 9 | cnt = 0 10 | 11 | for key, values in graph.items(): 12 | for i in values: 13 | indegree[i] += 1 14 | 15 | for i in range(len(indegree)): 16 | if indegree[i] == 0: 17 | queue.append(i) 18 | 19 | while queue: 20 | vertex = queue.pop(0) 21 | cnt += 1 22 | topo.append(vertex) 23 | for x in graph[vertex]: 24 | indegree[x] -= 1 25 | if indegree[x] == 0: 26 | queue.append(x) 27 | 28 | if cnt != len(graph): 29 | print("Cycle exists") 30 | else: 31 | print(topo) 32 | 33 | 34 | # Adjacency List of Graph 35 | graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} 36 | topologicalSort(graph) 37 | -------------------------------------------------------------------------------- /graphs/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, num_edges = 9, 14 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, num_edges, 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 | -------------------------------------------------------------------------------- /graphs/tests/test_min_spanning_tree_prim.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst 4 | 5 | 6 | def test_prim_successful_result(): 7 | num_nodes, num_edges = 9, 14 # noqa: F841 8 | edges = [ 9 | [0, 1, 4], 10 | [0, 7, 8], 11 | [1, 2, 8], 12 | [7, 8, 7], 13 | [7, 6, 1], 14 | [2, 8, 2], 15 | [8, 6, 6], 16 | [2, 3, 7], 17 | [2, 5, 4], 18 | [6, 5, 2], 19 | [3, 5, 14], 20 | [3, 4, 9], 21 | [5, 4, 10], 22 | [1, 7, 11], 23 | ] 24 | 25 | adjancency = defaultdict(list) 26 | for node1, node2, cost in edges: 27 | adjancency[node1].append([node2, cost]) 28 | adjancency[node2].append([node1, cost]) 29 | 30 | result = mst(adjancency) 31 | 32 | expected = [ 33 | [7, 6, 1], 34 | [2, 8, 2], 35 | [6, 5, 2], 36 | [0, 1, 4], 37 | [2, 5, 4], 38 | [2, 3, 7], 39 | [0, 7, 8], 40 | [3, 4, 9], 41 | ] 42 | 43 | for answer in expected: 44 | edge = tuple(answer[:2]) 45 | reverse = tuple(edge[::-1]) 46 | assert edge in result or reverse in result 47 | -------------------------------------------------------------------------------- /hashes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/hashes/__init__.py -------------------------------------------------------------------------------- /hashes/adler32.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. 3 | Compared to a cyclic redundancy check of the same length, it trades reliability for 4 | speed (preferring the latter). 5 | Adler-32 is more reliable than Fletcher-16, and slightly less reliable than 6 | Fletcher-32.[2] 7 | 8 | source: https://en.wikipedia.org/wiki/Adler-32 9 | """ 10 | 11 | 12 | def adler32(plain_text: str) -> str: 13 | """ 14 | Function implements adler-32 hash. 15 | Itterates and evaluates new value for each character 16 | 17 | >>> adler32('Algorithms') 18 | 363791387 19 | 20 | >>> adler32('go adler em all') 21 | 708642122 22 | """ 23 | MOD_ADLER = 65521 24 | a = 1 25 | b = 0 26 | for plain_chr in plain_text: 27 | a = (a + ord(plain_chr)) % MOD_ADLER 28 | b = (b + a) % MOD_ADLER 29 | return (b << 16) | a 30 | -------------------------------------------------------------------------------- /hashes/djb2.py: -------------------------------------------------------------------------------- 1 | """ 2 | This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c 3 | Another version of this algorithm (now favored by Bernstein) uses xor: 4 | hash(i) = hash(i - 1) * 33 ^ str[i]; 5 | 6 | First Magic constant 33: 7 | It has never been adequately explained. 8 | It's magic because it works better than many other constants, prime or not. 9 | 10 | Second Magic Constant 5381: 11 | 12 | 1. odd number 13 | 2. prime number 14 | 3. deficient number 15 | 4. 001/010/100/000/101 b 16 | 17 | source: http://www.cse.yorku.ca/~oz/hash.html 18 | """ 19 | 20 | 21 | def djb2(s: str) -> int: 22 | """ 23 | Implementation of djb2 hash algorithm that 24 | is popular because of it's magic constants. 25 | 26 | >>> djb2('Algorithms') 27 | 3782405311 28 | 29 | >>> djb2('scramble bits') 30 | 1609059040 31 | """ 32 | hash = 5381 33 | for x in s: 34 | hash = ((hash << 5) + hash) + ord(x) 35 | return hash & 0xFFFFFFFF 36 | -------------------------------------------------------------------------------- /knapsack/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/knapsack/__init__.py -------------------------------------------------------------------------------- /knapsack/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/knapsack/tests/__init__.py -------------------------------------------------------------------------------- /linear_algebra/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/linear_algebra/__init__.py -------------------------------------------------------------------------------- /linear_algebra/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/linear_algebra/src/__init__.py -------------------------------------------------------------------------------- /machine_learning/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/machine_learning/__init__.py -------------------------------------------------------------------------------- /machine_learning/forecasting/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/machine_learning/forecasting/__init__.py -------------------------------------------------------------------------------- /machine_learning/knn_sklearn.py: -------------------------------------------------------------------------------- 1 | from sklearn.datasets import load_iris 2 | from sklearn.model_selection import train_test_split 3 | from sklearn.neighbors import KNeighborsClassifier 4 | 5 | # Load iris file 6 | iris = load_iris() 7 | iris.keys() 8 | 9 | 10 | print(f"Target names: \n {iris.target_names} ") 11 | print(f"\n Features: \n {iris.feature_names}") 12 | 13 | # Train set e Test set 14 | X_train, X_test, y_train, y_test = train_test_split( 15 | iris["data"], iris["target"], random_state=4 16 | ) 17 | 18 | # KNN 19 | 20 | knn = KNeighborsClassifier(n_neighbors=1) 21 | knn.fit(X_train, y_train) 22 | 23 | # new array to test 24 | X_new = [[1, 2, 1, 4], [2, 3, 4, 5]] 25 | 26 | prediction = knn.predict(X_new) 27 | 28 | print( 29 | "\nNew array: \n {}" 30 | "\n\nTarget Names Prediction: \n {}".format(X_new, iris["target_names"][prediction]) 31 | ) 32 | -------------------------------------------------------------------------------- /machine_learning/lstm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/machine_learning/lstm/__init__.py -------------------------------------------------------------------------------- /machine_learning/multilayer_perceptron_classifier.py: -------------------------------------------------------------------------------- 1 | from sklearn.neural_network import MLPClassifier 2 | 3 | X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] 4 | y = [0, 1, 0, 0] 5 | 6 | 7 | clf = MLPClassifier( 8 | solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1 9 | ) 10 | 11 | clf.fit(X, y) 12 | 13 | 14 | test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] 15 | Y = clf.predict(test) 16 | 17 | 18 | def wrapper(Y): 19 | """ 20 | >>> wrapper(Y) 21 | [0, 0, 1] 22 | """ 23 | return list(Y) 24 | 25 | 26 | if __name__ == "__main__": 27 | import doctest 28 | 29 | doctest.testmod() 30 | -------------------------------------------------------------------------------- /maths/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/maths/__init__.py -------------------------------------------------------------------------------- /maths/abs.py: -------------------------------------------------------------------------------- 1 | """Absolute Value.""" 2 | 3 | 4 | def abs_val(num): 5 | """ 6 | Find the absolute value of a number. 7 | 8 | >>> abs_val(-5.1) 9 | 5.1 10 | >>> abs_val(-5) == abs_val(5) 11 | True 12 | >>> abs_val(0) 13 | 0 14 | """ 15 | return -num if num < 0 else num 16 | 17 | 18 | def test_abs_val(): 19 | """ 20 | >>> test_abs_val() 21 | """ 22 | assert 0 == abs_val(0) 23 | assert 34 == abs_val(34) 24 | assert 100000000000 == abs_val(-100000000000) 25 | 26 | 27 | if __name__ == "__main__": 28 | print(abs_val(-34)) # --> 34 29 | -------------------------------------------------------------------------------- /maths/abs_max.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | 4 | def abs_max(x: list[int]) -> int: 5 | """ 6 | >>> abs_max([0,5,1,11]) 7 | 11 8 | >>> abs_max([3,-10,-2]) 9 | -10 10 | """ 11 | j = x[0] 12 | for i in x: 13 | if abs(i) > abs(j): 14 | j = i 15 | return j 16 | 17 | 18 | def abs_max_sort(x): 19 | """ 20 | >>> abs_max_sort([0,5,1,11]) 21 | 11 22 | >>> abs_max_sort([3,-10,-2]) 23 | -10 24 | """ 25 | return sorted(x, key=abs)[-1] 26 | 27 | 28 | def main(): 29 | a = [1, 2, -11] 30 | assert abs_max(a) == -11 31 | assert abs_max_sort(a) == -11 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /maths/abs_min.py: -------------------------------------------------------------------------------- 1 | from .abs import abs_val 2 | 3 | 4 | def absMin(x): 5 | """ 6 | >>> absMin([0,5,1,11]) 7 | 0 8 | >>> absMin([3,-10,-2]) 9 | -2 10 | """ 11 | j = x[0] 12 | for i in x: 13 | if abs_val(i) < abs_val(j): 14 | j = i 15 | return j 16 | 17 | 18 | def main(): 19 | a = [-3, -1, 2, -11] 20 | print(absMin(a)) # = -1 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /maths/add.py: -------------------------------------------------------------------------------- 1 | """ 2 | Just to check 3 | """ 4 | 5 | 6 | def add(a, b): 7 | """ 8 | >>> add(2, 2) 9 | 4 10 | >>> add(2, -2) 11 | 0 12 | """ 13 | return a + b 14 | 15 | 16 | if __name__ == "__main__": 17 | a = 5 18 | b = 6 19 | print(f"The sum of {a} + {b} is {add(a, b)}") 20 | -------------------------------------------------------------------------------- /maths/average_mean.py: -------------------------------------------------------------------------------- 1 | """Find mean of a list of numbers.""" 2 | 3 | 4 | def average(nums): 5 | """Find mean of a list of numbers.""" 6 | return sum(nums) / len(nums) 7 | 8 | 9 | def test_average(): 10 | """ 11 | >>> test_average() 12 | """ 13 | assert 12.0 == average([3, 6, 9, 12, 15, 18, 21]) 14 | assert 20 == average([5, 10, 15, 20, 25, 30, 35]) 15 | assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8]) 16 | 17 | 18 | if __name__ == "__main__": 19 | """Call average module to find mean of a specific list of numbers.""" 20 | print(average([2, 4, 6, 8, 20, 50, 70])) 21 | -------------------------------------------------------------------------------- /maths/average_median.py: -------------------------------------------------------------------------------- 1 | def median(nums): 2 | """ 3 | Find median of a list of numbers. 4 | 5 | >>> median([0]) 6 | 0 7 | >>> median([4,1,3,2]) 8 | 2.5 9 | >>> median([2, 70, 6, 50, 20, 8, 4]) 10 | 8 11 | 12 | Args: 13 | nums: List of nums 14 | 15 | Returns: 16 | Median. 17 | """ 18 | sorted_list = sorted(nums) 19 | length = len(sorted_list) 20 | mid_index = length >> 1 21 | return ( 22 | (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 23 | if length % 2 == 0 24 | else sorted_list[mid_index] 25 | ) 26 | 27 | 28 | def main(): 29 | import doctest 30 | 31 | doctest.testmod() 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /maths/average_mode.py: -------------------------------------------------------------------------------- 1 | import statistics 2 | 3 | 4 | def mode(input_list): # Defining function "mode." 5 | """This function returns the mode(Mode as in the measures of 6 | central tendency) of the input data. 7 | 8 | The input list may contain any Datastructure or any Datatype. 9 | 10 | >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 11 | >>> mode(input_list) 12 | 2 13 | >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 14 | >>> mode(input_list) == statistics.mode(input_list) 15 | True 16 | """ 17 | # Copying input_list to check with the index number later. 18 | check_list = input_list.copy() 19 | result = list() # Empty list to store the counts of elements in input_list 20 | for x in input_list: 21 | result.append(input_list.count(x)) 22 | input_list.remove(x) 23 | y = max(result) # Gets the maximum value in the result list. 24 | # Returns the value with the maximum number of repetitions. 25 | return check_list[result.index(y)] 26 | 27 | 28 | if __name__ == "__main__": 29 | data = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 30 | print(mode(data)) 31 | print(statistics.mode(data)) 32 | -------------------------------------------------------------------------------- /maths/binary_exp_mod.py: -------------------------------------------------------------------------------- 1 | def bin_exp_mod(a, n, b): 2 | """ 3 | >>> bin_exp_mod(3, 4, 5) 4 | 1 5 | >>> bin_exp_mod(7, 13, 10) 6 | 7 7 | """ 8 | # mod b 9 | assert not (b == 0), "This cannot accept modulo that is == 0" 10 | if n == 0: 11 | return 1 12 | 13 | if n % 2 == 1: 14 | return (bin_exp_mod(a, n - 1, b) * a) % b 15 | 16 | r = bin_exp_mod(a, n / 2, b) 17 | return (r * r) % b 18 | 19 | 20 | if __name__ == "__main__": 21 | try: 22 | BASE = int(input("Enter Base : ").strip()) 23 | POWER = int(input("Enter Power : ").strip()) 24 | MODULO = int(input("Enter Modulo : ").strip()) 25 | except ValueError: 26 | print("Invalid literal for integer") 27 | 28 | print(bin_exp_mod(BASE, POWER, MODULO)) 29 | -------------------------------------------------------------------------------- /maths/binary_exponentiation.py: -------------------------------------------------------------------------------- 1 | """Binary Exponentiation.""" 2 | 3 | # Author : Junth Basnet 4 | # Time Complexity : O(logn) 5 | 6 | 7 | def binary_exponentiation(a, n): 8 | 9 | if n == 0: 10 | return 1 11 | 12 | elif n % 2 == 1: 13 | return binary_exponentiation(a, n - 1) * a 14 | 15 | else: 16 | b = binary_exponentiation(a, n / 2) 17 | return b * b 18 | 19 | 20 | if __name__ == "__main__": 21 | try: 22 | BASE = int(input("Enter Base : ").strip()) 23 | POWER = int(input("Enter Power : ").strip()) 24 | except ValueError: 25 | print("Invalid literal for integer") 26 | 27 | RESULT = binary_exponentiation(BASE, POWER) 28 | print(f"{BASE}^({POWER}) : {RESULT}") 29 | -------------------------------------------------------------------------------- /maths/binomial_coefficient.py: -------------------------------------------------------------------------------- 1 | def binomial_coefficient(n, r): 2 | """ 3 | Find binomial coefficient using pascals triangle. 4 | 5 | >>> binomial_coefficient(10, 5) 6 | 252 7 | """ 8 | C = [0 for i in range(r + 1)] 9 | # nc0 = 1 10 | C[0] = 1 11 | for i in range(1, n + 1): 12 | # to compute current row from previous row. 13 | j = min(i, r) 14 | while j > 0: 15 | C[j] += C[j - 1] 16 | j -= 1 17 | return C[r] 18 | 19 | 20 | print(binomial_coefficient(n=10, r=5)) 21 | -------------------------------------------------------------------------------- /maths/ceil.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Floor_and_ceiling_functions 3 | """ 4 | 5 | 6 | def ceil(x) -> int: 7 | """ 8 | Return the ceiling of x as an Integral. 9 | 10 | :param x: the number 11 | :return: the smallest integer >= x. 12 | 13 | >>> import math 14 | >>> all(ceil(n) == math.ceil(n) for n 15 | ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) 16 | True 17 | """ 18 | return int(x) if x - int(x) <= 0 else int(x) + 1 19 | 20 | 21 | if __name__ == "__main__": 22 | import doctest 23 | 24 | doctest.testmod() 25 | -------------------------------------------------------------------------------- /maths/explicit_euler.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def explicit_euler(ode_func, y0, x0, step_size, x_end): 5 | """ 6 | Calculate numeric solution at each step to an ODE using Euler's Method 7 | 8 | https://en.wikipedia.org/wiki/Euler_method 9 | 10 | Arguments: 11 | ode_func -- The ode as a function of x and y 12 | y0 -- the initial value for y 13 | x0 -- the initial value for x 14 | stepsize -- the increment value for x 15 | x_end -- the end value for x 16 | 17 | >>> # the exact solution is math.exp(x) 18 | >>> def f(x, y): 19 | ... return y 20 | >>> y0 = 1 21 | >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) 22 | >>> y[-1] 23 | 144.77277243257308 24 | """ 25 | N = int(np.ceil((x_end - x0) / step_size)) 26 | y = np.zeros((N + 1,)) 27 | y[0] = y0 28 | x = x0 29 | 30 | for k in range(N): 31 | y[k + 1] = y[k] + step_size * ode_func(x, y[k]) 32 | x += step_size 33 | 34 | return y 35 | 36 | 37 | if __name__ == "__main__": 38 | import doctest 39 | 40 | doctest.testmod() 41 | -------------------------------------------------------------------------------- /maths/factorial_iterative.py: -------------------------------------------------------------------------------- 1 | # factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial 2 | 3 | 4 | def factorial(n: int) -> int: 5 | """ 6 | >>> import math 7 | >>> all(factorial(i) == math.factorial(i) for i in range(20)) 8 | True 9 | >>> factorial(0.1) 10 | Traceback (most recent call last): 11 | ... 12 | ValueError: factorial() only accepts integral values 13 | >>> factorial(-1) 14 | Traceback (most recent call last): 15 | ... 16 | ValueError: factorial() not defined for negative values 17 | """ 18 | if n != int(n): 19 | raise ValueError("factorial() only accepts integral values") 20 | if n < 0: 21 | raise ValueError("factorial() not defined for negative values") 22 | value = 1 23 | for i in range(1, n + 1): 24 | value *= i 25 | return value 26 | 27 | 28 | if __name__ == "__main__": 29 | n = int(input("Enter a positive integer: ").strip() or 0) 30 | print(f"factorial{n} is {factorial(n)}") 31 | -------------------------------------------------------------------------------- /maths/factorial_python.py: -------------------------------------------------------------------------------- 1 | def factorial(input_number: int) -> int: 2 | """ 3 | Calculate the factorial of specified number 4 | 5 | >>> factorial(1) 6 | 1 7 | >>> factorial(6) 8 | 720 9 | >>> factorial(0) 10 | 1 11 | >>> factorial(-1) 12 | Traceback (most recent call last): 13 | ... 14 | ValueError: factorial() not defined for negative values 15 | >>> factorial(0.1) 16 | Traceback (most recent call last): 17 | ... 18 | ValueError: factorial() only accepts integral values 19 | """ 20 | 21 | if input_number < 0: 22 | raise ValueError("factorial() not defined for negative values") 23 | if not isinstance(input_number, int): 24 | raise ValueError("factorial() only accepts integral values") 25 | result = 1 26 | for i in range(1, input_number): 27 | result = result * (i + 1) 28 | return result 29 | 30 | 31 | if __name__ == "__main__": 32 | import doctest 33 | 34 | doctest.testmod() 35 | -------------------------------------------------------------------------------- /maths/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | def factorial(n: int) -> int: 2 | """ 3 | Calculate the factorial of a positive integer 4 | https://en.wikipedia.org/wiki/Factorial 5 | 6 | >>> import math 7 | >>> all(factorial(i) == math.factorial(i) for i in range(20)) 8 | True 9 | >>> factorial(0.1) 10 | Traceback (most recent call last): 11 | ... 12 | ValueError: factorial() only accepts integral values 13 | >>> factorial(-1) 14 | Traceback (most recent call last): 15 | ... 16 | ValueError: factorial() not defined for negative values 17 | """ 18 | if not isinstance(n, int): 19 | raise ValueError("factorial() only accepts integral values") 20 | if n < 0: 21 | raise ValueError("factorial() not defined for negative values") 22 | return 1 if n == 0 or n == 1 else n * factorial(n - 1) 23 | 24 | 25 | if __name__ == "__main__": 26 | import doctest 27 | 28 | doctest.testmod() 29 | -------------------------------------------------------------------------------- /maths/factors.py: -------------------------------------------------------------------------------- 1 | def factors_of_a_number(num: int) -> list: 2 | """ 3 | >>> factors_of_a_number(1) 4 | [1] 5 | >>> factors_of_a_number(5) 6 | [1, 5] 7 | >>> factors_of_a_number(24) 8 | [1, 2, 3, 4, 6, 8, 12, 24] 9 | >>> factors_of_a_number(-24) 10 | [] 11 | """ 12 | return [i for i in range(1, num + 1) if num % i == 0] 13 | 14 | 15 | if __name__ == "__main__": 16 | num = int(input("Enter a number to find its factors: ")) 17 | factors = factors_of_a_number(num) 18 | print(f"{num} has {len(factors)} factors: {', '.join(str(f) for f in factors)}") 19 | -------------------------------------------------------------------------------- /maths/fermat_little_theorem.py: -------------------------------------------------------------------------------- 1 | # Python program to show the usage of Fermat's little theorem in a division 2 | # According to Fermat's little theorem, (a / b) mod p always equals 3 | # a * (b ^ (p - 2)) mod p 4 | # Here we assume that p is a prime number, b divides a, and p doesn't divide b 5 | # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem 6 | 7 | 8 | def binary_exponentiation(a, n, mod): 9 | 10 | if n == 0: 11 | return 1 12 | 13 | elif n % 2 == 1: 14 | return (binary_exponentiation(a, n - 1, mod) * a) % mod 15 | 16 | else: 17 | b = binary_exponentiation(a, n / 2, mod) 18 | return (b * b) % mod 19 | 20 | 21 | # a prime number 22 | p = 701 23 | 24 | a = 1000000000 25 | b = 10 26 | 27 | # using binary exponentiation function, O(log(p)): 28 | print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) 29 | 30 | # using Python operators: 31 | print((a / b) % p == (a * b ** (p - 2)) % p) 32 | -------------------------------------------------------------------------------- /maths/fibonacci_sequence_recursion.py: -------------------------------------------------------------------------------- 1 | # Fibonacci Sequence Using Recursion 2 | 3 | 4 | def recur_fibo(n: int) -> int: 5 | """ 6 | >>> [recur_fibo(i) for i in range(12)] 7 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 8 | """ 9 | return n if n <= 1 else recur_fibo(n - 1) + recur_fibo(n - 2) 10 | 11 | 12 | def main() -> None: 13 | limit = int(input("How many terms to include in fibonacci series: ")) 14 | if limit > 0: 15 | print(f"The first {limit} terms of the fibonacci series are as follows:") 16 | print([recur_fibo(n) for n in range(limit)]) 17 | else: 18 | print("Please enter a positive integer: ") 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /maths/find_max.py: -------------------------------------------------------------------------------- 1 | # NguyenU 2 | 3 | 4 | def find_max(nums): 5 | """ 6 | >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): 7 | ... find_max(nums) == max(nums) 8 | True 9 | True 10 | True 11 | True 12 | """ 13 | max_num = nums[0] 14 | for x in nums: 15 | if x > max_num: 16 | max_num = x 17 | return max_num 18 | 19 | 20 | def main(): 21 | print(find_max([2, 4, 9, 7, 19, 94, 5])) # 94 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /maths/find_max_recursion.py: -------------------------------------------------------------------------------- 1 | # Divide and Conquer algorithm 2 | def find_max(nums, left, right): 3 | """ 4 | find max value in list 5 | :param nums: contains elements 6 | :param left: index of first element 7 | :param right: index of last element 8 | :return: max in nums 9 | 10 | >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 11 | >>> find_max(nums, 0, len(nums) - 1) == max(nums) 12 | True 13 | """ 14 | if left == right: 15 | return nums[left] 16 | mid = (left + right) >> 1 # the middle 17 | left_max = find_max(nums, left, mid) # find max in range[left, mid] 18 | right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] 19 | 20 | return left_max if left_max >= right_max else right_max 21 | 22 | 23 | if __name__ == "__main__": 24 | nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 25 | assert find_max(nums, 0, len(nums) - 1) == 10 26 | -------------------------------------------------------------------------------- /maths/find_min.py: -------------------------------------------------------------------------------- 1 | def find_min(nums): 2 | """ 3 | Find Minimum Number in a List 4 | :param nums: contains elements 5 | :return: min number in list 6 | 7 | >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): 8 | ... find_min(nums) == min(nums) 9 | True 10 | True 11 | True 12 | True 13 | """ 14 | min_num = nums[0] 15 | for num in nums: 16 | if min_num > num: 17 | min_num = num 18 | return min_num 19 | 20 | 21 | def main(): 22 | assert find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) == -56 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /maths/find_min_recursion.py: -------------------------------------------------------------------------------- 1 | # Divide and Conquer algorithm 2 | def find_min(nums, left, right): 3 | """ 4 | find min value in list 5 | :param nums: contains elements 6 | :param left: index of first element 7 | :param right: index of last element 8 | :return: min in nums 9 | 10 | >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 11 | >>> find_min(nums, 0, len(nums) - 1) == min(nums) 12 | True 13 | """ 14 | if left == right: 15 | return nums[left] 16 | mid = (left + right) >> 1 # the middle 17 | left_min = find_min(nums, left, mid) # find min in range[left, mid] 18 | right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right] 19 | 20 | return left_min if left_min <= right_min else right_min 21 | 22 | 23 | if __name__ == "__main__": 24 | nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 25 | assert find_min(nums, 0, len(nums) - 1) == 1 26 | -------------------------------------------------------------------------------- /maths/floor.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Floor_and_ceiling_functions 3 | """ 4 | 5 | 6 | def floor(x) -> 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/hardy_ramanujanalgo.py: -------------------------------------------------------------------------------- 1 | # This theorem states that the number of prime factors of n 2 | # will be approximately log(log(n)) for most natural numbers n 3 | 4 | import math 5 | 6 | 7 | def exactPrimeFactorCount(n): 8 | """ 9 | >>> exactPrimeFactorCount(51242183) 10 | 3 11 | """ 12 | count = 0 13 | if n % 2 == 0: 14 | count += 1 15 | while n % 2 == 0: 16 | n = int(n / 2) 17 | # the n input value must be odd so that 18 | # we can skip one element (ie i += 2) 19 | 20 | i = 3 21 | 22 | while i <= int(math.sqrt(n)): 23 | if n % i == 0: 24 | count += 1 25 | while n % i == 0: 26 | n = int(n / i) 27 | i = i + 2 28 | 29 | # this condition checks the prime 30 | # number n is greater than 2 31 | 32 | if n > 2: 33 | count += 1 34 | return count 35 | 36 | 37 | if __name__ == "__main__": 38 | n = 51242183 39 | print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}") 40 | print("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n)))) 41 | 42 | """ 43 | The number of distinct prime factors is/are 3 44 | The value of log(log(n)) is 2.8765 45 | """ 46 | -------------------------------------------------------------------------------- /maths/images/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/maths/images/__init__.py -------------------------------------------------------------------------------- /maths/images/gaussian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/maths/images/gaussian.png -------------------------------------------------------------------------------- /maths/is_square_free.py: -------------------------------------------------------------------------------- 1 | """ 2 | References: wikipedia:square free number 3 | python/black : True 4 | flake8 : True 5 | """ 6 | from __future__ import annotations 7 | 8 | 9 | def is_square_free(factors: list[int]) -> bool: 10 | """ 11 | # doctest: +NORMALIZE_WHITESPACE 12 | This functions takes a list of prime factors as input. 13 | returns True if the factors are square free. 14 | >>> is_square_free([1, 1, 2, 3, 4]) 15 | False 16 | 17 | These are wrong but should return some value 18 | it simply checks for repition in the numbers. 19 | >>> is_square_free([1, 3, 4, 'sd', 0.0]) 20 | True 21 | 22 | >>> is_square_free([1, 0.5, 2, 0.0]) 23 | True 24 | >>> is_square_free([1, 2, 2, 5]) 25 | False 26 | >>> is_square_free('asd') 27 | True 28 | >>> is_square_free(24) 29 | Traceback (most recent call last): 30 | ... 31 | TypeError: 'int' object is not iterable 32 | """ 33 | return len(set(factors)) == len(factors) 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | -------------------------------------------------------------------------------- /maths/karatsuba.py: -------------------------------------------------------------------------------- 1 | """ Multiply two numbers using Karatsuba algorithm """ 2 | 3 | 4 | def karatsuba(a, b): 5 | """ 6 | >>> karatsuba(15463, 23489) == 15463 * 23489 7 | True 8 | >>> karatsuba(3, 9) == 3 * 9 9 | True 10 | """ 11 | if len(str(a)) == 1 or len(str(b)) == 1: 12 | return a * b 13 | else: 14 | m1 = max(len(str(a)), len(str(b))) 15 | m2 = m1 // 2 16 | 17 | a1, a2 = divmod(a, 10 ** m2) 18 | b1, b2 = divmod(b, 10 ** m2) 19 | 20 | x = karatsuba(a2, b2) 21 | y = karatsuba((a1 + a2), (b1 + b2)) 22 | z = karatsuba(a1, b1) 23 | 24 | return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) 25 | 26 | 27 | def main(): 28 | print(karatsuba(15463, 23489)) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /maths/largest_of_very_large_numbers.py: -------------------------------------------------------------------------------- 1 | # Author: Abhijeeth S 2 | 3 | import math 4 | 5 | 6 | def res(x, y): 7 | if 0 not in (x, y): 8 | # We use the relation x^y = y*log10(x), where 10 is the base. 9 | return y * math.log10(x) 10 | else: 11 | if x == 0: # 0 raised to any number is 0 12 | return 0 13 | elif y == 0: 14 | return 1 # any number raised to 0 is 1 15 | 16 | 17 | if __name__ == "__main__": # Main function 18 | # Read two numbers from input and typecast them to int using map function. 19 | # Here x is the base and y is the power. 20 | prompt = "Enter the base and the power separated by a comma: " 21 | x1, y1 = map(int, input(prompt).split(",")) 22 | x2, y2 = map(int, input(prompt).split(",")) 23 | 24 | # We find the log of each number, using the function res(), which takes two 25 | # arguments. 26 | res1 = res(x1, y1) 27 | res2 = res(x2, y2) 28 | 29 | # We check for the largest number 30 | if res1 > res2: 31 | print("Largest number is", x1, "^", y1) 32 | elif res2 > res1: 33 | print("Largest number is", x2, "^", y2) 34 | else: 35 | print("Both are equal") 36 | -------------------------------------------------------------------------------- /maths/lucas_lehmer_primality_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne 3 | numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test 4 | 5 | A Mersenne number is a number that is one less than a power of two. 6 | That is M_p = 2^p - 1 7 | https://en.wikipedia.org/wiki/Mersenne_prime 8 | 9 | The Lucas–Lehmer test is the primality test used by the 10 | Great Internet Mersenne Prime Search (GIMPS) to locate large primes. 11 | """ 12 | 13 | 14 | # Primality test 2^p - 1 15 | # Return true if 2^p - 1 is prime 16 | def lucas_lehmer_test(p: int) -> bool: 17 | """ 18 | >>> lucas_lehmer_test(p=7) 19 | True 20 | 21 | >>> lucas_lehmer_test(p=11) 22 | False 23 | 24 | # M_11 = 2^11 - 1 = 2047 = 23 * 89 25 | """ 26 | 27 | if p < 2: 28 | raise ValueError("p should not be less than 2!") 29 | elif p == 2: 30 | return True 31 | 32 | s = 4 33 | M = (1 << p) - 1 34 | for i in range(p - 2): 35 | s = ((s * s) - 2) % M 36 | return s == 0 37 | 38 | 39 | if __name__ == "__main__": 40 | print(lucas_lehmer_test(7)) 41 | print(lucas_lehmer_test(11)) 42 | -------------------------------------------------------------------------------- /maths/mobius_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | References: https://en.wikipedia.org/wiki/M%C3%B6bius_function 3 | References: wikipedia:square free number 4 | python/black : True 5 | flake8 : True 6 | """ 7 | 8 | from maths.is_square_free import is_square_free 9 | from maths.prime_factors import prime_factors 10 | 11 | 12 | def mobius(n: int) -> int: 13 | """ 14 | Mobius function 15 | >>> mobius(24) 16 | 0 17 | >>> mobius(-1) 18 | 1 19 | >>> mobius('asd') 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: '<=' not supported between instances of 'int' and 'str' 23 | >>> mobius(10**400) 24 | 0 25 | >>> mobius(10**-400) 26 | 1 27 | >>> mobius(-1424) 28 | 1 29 | >>> mobius([1, '2', 2.0]) 30 | Traceback (most recent call last): 31 | ... 32 | TypeError: '<=' not supported between instances of 'int' and 'list' 33 | """ 34 | factors = prime_factors(n) 35 | if is_square_free(factors): 36 | return -1 if len(factors) % 2 else 1 37 | return 0 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | -------------------------------------------------------------------------------- /maths/modular_exponential.py: -------------------------------------------------------------------------------- 1 | """ 2 | Modular Exponential. 3 | Modular exponentiation is a type of exponentiation performed over a modulus. 4 | For more explanation, please check 5 | https://en.wikipedia.org/wiki/Modular_exponentiation 6 | """ 7 | 8 | """Calculate Modular Exponential.""" 9 | 10 | 11 | def modular_exponential(base: int, power: int, mod: int): 12 | """ 13 | >>> modular_exponential(5, 0, 10) 14 | 1 15 | >>> modular_exponential(2, 8, 7) 16 | 4 17 | >>> modular_exponential(3, -2, 9) 18 | -1 19 | """ 20 | 21 | if power < 0: 22 | return -1 23 | base %= mod 24 | result = 1 25 | 26 | while power > 0: 27 | if power & 1: 28 | result = (result * base) % mod 29 | power = power >> 1 30 | base = (base * base) % mod 31 | 32 | return result 33 | 34 | 35 | def main(): 36 | """Call Modular Exponential Function.""" 37 | print(modular_exponential(3, 200, 13)) 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | 45 | main() 46 | -------------------------------------------------------------------------------- /maths/perfect_cube.py: -------------------------------------------------------------------------------- 1 | def perfect_cube(n: int) -> bool: 2 | """ 3 | Check if a number is a perfect cube or not. 4 | 5 | >>> perfect_cube(27) 6 | True 7 | >>> perfect_cube(4) 8 | False 9 | """ 10 | val = n ** (1 / 3) 11 | return (val * val * val) == n 12 | 13 | 14 | if __name__ == "__main__": 15 | print(perfect_cube(27)) 16 | print(perfect_cube(4)) 17 | -------------------------------------------------------------------------------- /maths/perfect_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | == Perfect Number == 3 | In number theory, a perfect number is a positive integer that is equal to the sum of 4 | its positive divisors, excluding the number itself. 5 | For example: 6 ==> divisors[1, 2, 3, 6] 6 | Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 7 | So, 6 is a Perfect Number 8 | 9 | Other examples of Perfect Numbers: 28, 486, ... 10 | 11 | https://en.wikipedia.org/wiki/Perfect_number 12 | """ 13 | 14 | 15 | def perfect(number: int) -> bool: 16 | """ 17 | >>> perfect(27) 18 | False 19 | >>> perfect(28) 20 | True 21 | >>> perfect(29) 22 | False 23 | 24 | Start from 1 because dividing by 0 will raise ZeroDivisionError. 25 | A number at most can be divisible by the half of the number except the number 26 | itself. For example, 6 is at most can be divisible by 3 except by 6 itself. 27 | """ 28 | return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number 29 | 30 | 31 | if __name__ == "__main__": 32 | print("Program to check whether a number is a Perfect number or not...") 33 | number = int(input("Enter number: ").strip()) 34 | print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.") 35 | -------------------------------------------------------------------------------- /maths/power_using_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | == Raise base to the power of exponent using recursion == 3 | Input --> 4 | Enter the base: 3 5 | Enter the exponent: 4 6 | Output --> 7 | 3 to the power of 4 is 81 8 | Input --> 9 | Enter the base: 2 10 | Enter the exponent: 0 11 | Output --> 12 | 2 to the power of 0 is 1 13 | """ 14 | 15 | 16 | def power(base: int, exponent: int) -> float: 17 | """ 18 | power(3, 4) 19 | 81 20 | >>> power(2, 0) 21 | 1 22 | >>> all(power(base, exponent) == pow(base, exponent) 23 | ... for base in range(-10, 10) for exponent in range(10)) 24 | True 25 | """ 26 | return base * power(base, (exponent - 1)) if exponent else 1 27 | 28 | 29 | if __name__ == "__main__": 30 | print("Raise base to the power of exponent using recursion...") 31 | base = int(input("Enter the base: ").strip()) 32 | exponent = int(input("Enter the exponent: ").strip()) 33 | result = power(base, abs(exponent)) 34 | if exponent < 0: # power() does not properly deal w/ negative exponents 35 | result = 1 / result 36 | print(f"{base} to the power of {exponent} is {result}") 37 | -------------------------------------------------------------------------------- /maths/prime_sieve_eratosthenes.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | """ 4 | Sieve of Eratosthenes 5 | 6 | Input : n =10 7 | Output: 2 3 5 7 8 | 9 | Input : n = 20 10 | Output: 2 3 5 7 11 13 17 19 11 | 12 | you can read in detail about this at 13 | https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 14 | """ 15 | 16 | 17 | def prime_sieve_eratosthenes(num): 18 | """ 19 | print the prime numbers up to n 20 | 21 | >>> prime_sieve_eratosthenes(10) 22 | 2,3,5,7, 23 | >>> prime_sieve_eratosthenes(20) 24 | 2,3,5,7,11,13,17,19, 25 | """ 26 | 27 | primes = [True for i in range(num + 1)] 28 | p = 2 29 | 30 | while p * p <= num: 31 | if primes[p]: 32 | for i in range(p * p, num + 1, p): 33 | primes[i] = False 34 | p += 1 35 | 36 | for prime in range(2, num + 1): 37 | if primes[prime]: 38 | print(prime, end=",") 39 | 40 | 41 | if __name__ == "__main__": 42 | import doctest 43 | 44 | doctest.testmod() 45 | num = int(input()) 46 | 47 | prime_sieve_eratosthenes(num) 48 | -------------------------------------------------------------------------------- /maths/pythagoras.py: -------------------------------------------------------------------------------- 1 | """Uses Pythagoras theorem to calculate the distance between two points in space.""" 2 | 3 | import math 4 | 5 | 6 | class Point: 7 | def __init__(self, x, y, z): 8 | self.x = x 9 | self.y = y 10 | self.z = z 11 | 12 | def __repr__(self) -> str: 13 | return f"Point({self.x}, {self.y}, {self.z})" 14 | 15 | 16 | def distance(a: Point, b: Point) -> float: 17 | return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) 18 | 19 | 20 | def test_distance() -> None: 21 | """ 22 | >>> point1 = Point(2, -1, 7) 23 | >>> point2 = Point(1, -3, 5) 24 | >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") 25 | Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 26 | """ 27 | pass 28 | 29 | 30 | if __name__ == "__main__": 31 | import doctest 32 | 33 | doctest.testmod() 34 | -------------------------------------------------------------------------------- /maths/quadratic_equations_complex_numbers.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from cmath import sqrt 4 | 5 | 6 | def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: 7 | """ 8 | Given the numerical coefficients a, b and c, 9 | calculates the roots for any quadratic equation of the form ax^2 + bx + c 10 | 11 | >>> quadratic_roots(a=1, b=3, c=-4) 12 | (1.0, -4.0) 13 | >>> quadratic_roots(5, 6, 1) 14 | (-0.2, -1.0) 15 | >>> quadratic_roots(1, -6, 25) 16 | ((3+4j), (3-4j)) 17 | """ 18 | 19 | if a == 0: 20 | raise ValueError("Coefficient 'a' must not be zero.") 21 | delta = b * b - 4 * a * c 22 | 23 | root_1 = (-b + sqrt(delta)) / (2 * a) 24 | root_2 = (-b - sqrt(delta)) / (2 * a) 25 | 26 | return ( 27 | root_1.real if not root_1.imag else root_1, 28 | root_2.real if not root_2.imag else root_2, 29 | ) 30 | 31 | 32 | def main(): 33 | solutions = quadratic_roots(a=5, b=6, c=1) 34 | print("The solutions are: {} and {}".format(*solutions)) 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /maths/radians.py: -------------------------------------------------------------------------------- 1 | from math import pi 2 | 3 | 4 | def radians(degree: float) -> float: 5 | """ 6 | Coverts the given angle from degrees to radians 7 | https://en.wikipedia.org/wiki/Radian 8 | 9 | >>> radians(180) 10 | 3.141592653589793 11 | >>> radians(92) 12 | 1.6057029118347832 13 | >>> radians(274) 14 | 4.782202150464463 15 | >>> radians(109.82) 16 | 1.9167205845401725 17 | 18 | >>> from math import radians as math_radians 19 | >>> all(abs(radians(i)-math_radians(i)) <= 0.00000001 for i in range(-2, 361)) 20 | True 21 | """ 22 | 23 | return degree / (180 / pi) 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /maths/runge_kutta.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def runge_kutta(f, y0, x0, h, x_end): 5 | """ 6 | Calculate the numeric solution at each step to the ODE f(x, y) using RK4 7 | 8 | https://en.wikipedia.org/wiki/Runge-Kutta_methods 9 | 10 | Arguments: 11 | f -- The ode as a function of x and y 12 | y0 -- the initial value for y 13 | x0 -- the initial value for x 14 | h -- the stepsize 15 | x_end -- the end value for x 16 | 17 | >>> # the exact solution is math.exp(x) 18 | >>> def f(x, y): 19 | ... return y 20 | >>> y0 = 1 21 | >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) 22 | >>> y[-1] 23 | 148.41315904125113 24 | """ 25 | N = int(np.ceil((x_end - x0) / h)) 26 | y = np.zeros((N + 1,)) 27 | y[0] = y0 28 | x = x0 29 | 30 | for k in range(N): 31 | k1 = f(x, y[k]) 32 | k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) 33 | k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) 34 | k4 = f(x + h, y[k] + h * k3) 35 | y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) 36 | x += h 37 | 38 | return y 39 | 40 | 41 | if __name__ == "__main__": 42 | import doctest 43 | 44 | doctest.testmod() 45 | -------------------------------------------------------------------------------- /maths/series/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/maths/series/__init__.py -------------------------------------------------------------------------------- /maths/sigmoid.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script demonstrates the implementation of the Sigmoid function. 3 | 4 | The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)). 5 | After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1. 6 | 7 | Script inspired from its corresponding Wikipedia article 8 | https://en.wikipedia.org/wiki/Sigmoid_function 9 | """ 10 | 11 | import numpy as np 12 | 13 | 14 | def sigmoid(vector: np.array) -> np.array: 15 | """ 16 | Implements the sigmoid function 17 | 18 | Parameters: 19 | vector (np.array): A numpy array of shape (1,n) 20 | consisting of real values 21 | 22 | Returns: 23 | sigmoid_vec (np.array): The input numpy array, after applying 24 | sigmoid. 25 | 26 | Examples: 27 | >>> sigmoid(np.array([-1.0, 1.0, 2.0])) 28 | array([0.26894142, 0.73105858, 0.88079708]) 29 | 30 | >>> sigmoid(np.array([0.0])) 31 | array([0.5]) 32 | """ 33 | return 1 / (1 + np.exp(-vector)) 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | -------------------------------------------------------------------------------- /maths/sum_of_arithmetic_series.py: -------------------------------------------------------------------------------- 1 | # DarkCoder 2 | def sum_of_series(first_term, common_diff, num_of_terms): 3 | """ 4 | Find the sum of n terms in an arithmetic progression. 5 | 6 | >>> sum_of_series(1, 1, 10) 7 | 55.0 8 | >>> sum_of_series(1, 10, 100) 9 | 49600.0 10 | """ 11 | sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) 12 | # formula for sum of series 13 | return sum 14 | 15 | 16 | def main(): 17 | print(sum_of_series(1, 1, 10)) 18 | 19 | 20 | if __name__ == "__main__": 21 | import doctest 22 | 23 | doctest.testmod() 24 | -------------------------------------------------------------------------------- /maths/sum_of_geometric_progression.py: -------------------------------------------------------------------------------- 1 | def sum_of_geometric_progression( 2 | first_term: int, common_ratio: int, num_of_terms: int 3 | ) -> float: 4 | """ " 5 | Return the sum of n terms in a geometric progression. 6 | >>> sum_of_geometric_progression(1, 2, 10) 7 | 1023.0 8 | >>> sum_of_geometric_progression(1, 10, 5) 9 | 11111.0 10 | >>> sum_of_geometric_progression(0, 2, 10) 11 | 0.0 12 | >>> sum_of_geometric_progression(1, 0, 10) 13 | 1.0 14 | >>> sum_of_geometric_progression(1, 2, 0) 15 | -0.0 16 | >>> sum_of_geometric_progression(-1, 2, 10) 17 | -1023.0 18 | >>> sum_of_geometric_progression(1, -2, 10) 19 | -341.0 20 | >>> sum_of_geometric_progression(1, 2, -10) 21 | -0.9990234375 22 | """ 23 | if common_ratio == 1: 24 | # Formula for sum if common ratio is 1 25 | return num_of_terms * first_term 26 | 27 | # Formula for finding sum of n terms of a GeometricProgression 28 | return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms) 29 | -------------------------------------------------------------------------------- /maths/test_prime_check.py: -------------------------------------------------------------------------------- 1 | """ 2 | Minimalist file that allows pytest to find and run the Test unittest. For details, see: 3 | http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery 4 | """ 5 | 6 | from .prime_check import Test 7 | 8 | Test() 9 | -------------------------------------------------------------------------------- /matrix/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/matrix/__init__.py -------------------------------------------------------------------------------- /matrix/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/matrix/tests/__init__.py -------------------------------------------------------------------------------- /matrix/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | mat_ops: tests for matrix operations 4 | -------------------------------------------------------------------------------- /networking_flow/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/networking_flow/__init__.py -------------------------------------------------------------------------------- /neural_network/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/neural_network/__init__.py -------------------------------------------------------------------------------- /other/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/other/__init__.py -------------------------------------------------------------------------------- /other/anagrams.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import os 3 | import pprint 4 | import time 5 | 6 | start_time = time.time() 7 | print("creating word list...") 8 | path = os.path.split(os.path.realpath(__file__)) 9 | with open(path[0] + "/words") as f: 10 | word_list = sorted(list({word.strip().lower() for word in f})) 11 | 12 | 13 | def signature(word): 14 | return "".join(sorted(word)) 15 | 16 | 17 | word_bysig = collections.defaultdict(list) 18 | for word in word_list: 19 | word_bysig[signature(word)].append(word) 20 | 21 | 22 | def anagram(my_word): 23 | return word_bysig[signature(my_word)] 24 | 25 | 26 | print("finding anagrams...") 27 | all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} 28 | 29 | print("writing anagrams to file...") 30 | with open("anagrams.txt", "w") as file: 31 | file.write("all_anagrams = ") 32 | file.write(pprint.pformat(all_anagrams)) 33 | 34 | total_time = round(time.time() - start_time, 2) 35 | print(("Done [", total_time, "seconds ]")) 36 | -------------------------------------------------------------------------------- /other/fischer_yates_shuffle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | The Fisher–Yates shuffle is an algorithm for generating a random permutation of a 4 | finite sequence. 5 | For more details visit 6 | wikipedia/Fischer-Yates-Shuffle. 7 | """ 8 | import random 9 | 10 | 11 | def FYshuffle(list): 12 | for i in range(len(list)): 13 | a = random.randint(0, len(list) - 1) 14 | b = random.randint(0, len(list) - 1) 15 | list[a], list[b] = list[b], list[a] 16 | return list 17 | 18 | 19 | if __name__ == "__main__": 20 | integers = [0, 1, 2, 3, 4, 5, 6, 7] 21 | strings = ["python", "says", "hello", "!"] 22 | print("Fisher-Yates Shuffle:") 23 | print("List", integers, strings) 24 | print("FY Shuffle", FYshuffle(integers), FYshuffle(strings)) 25 | -------------------------------------------------------------------------------- /other/largest_subarray_sum.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | 3 | 4 | def max_sub_array_sum(a: list, size: int = 0): 5 | """ 6 | >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) 7 | -3 8 | """ 9 | size = size or len(a) 10 | max_so_far = -maxsize - 1 11 | max_ending_here = 0 12 | for i in range(0, size): 13 | max_ending_here = max_ending_here + a[i] 14 | if max_so_far < max_ending_here: 15 | max_so_far = max_ending_here 16 | if max_ending_here < 0: 17 | max_ending_here = 0 18 | return max_so_far 19 | 20 | 21 | if __name__ == "__main__": 22 | a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] 23 | print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a)))) 24 | -------------------------------------------------------------------------------- /other/median_of_two_arrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def median_of_two_arrays(nums1: List[float], nums2: List[float]) -> float: 5 | """ 6 | >>> median_of_two_arrays([1, 2], [3]) 7 | 2 8 | >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 9 | 0.5 10 | >>> median_of_two_arrays([], [2.5, 1]) 11 | 1.75 12 | >>> median_of_two_arrays([], [0]) 13 | 0 14 | >>> median_of_two_arrays([], []) 15 | Traceback (most recent call last): 16 | ... 17 | IndexError: list index out of range 18 | """ 19 | all_numbers = sorted(nums1 + nums2) 20 | div, mod = divmod(len(all_numbers), 2) 21 | if mod == 1: 22 | return all_numbers[div] 23 | else: 24 | return (all_numbers[div] + all_numbers[div - 1]) / 2 25 | 26 | 27 | if __name__ == "__main__": 28 | import doctest 29 | 30 | doctest.testmod() 31 | array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] 32 | array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] 33 | print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}") 34 | -------------------------------------------------------------------------------- /other/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | def moveTower(height, fromPole, toPole, withPole): 2 | """ 3 | >>> moveTower(3, 'A', 'B', 'C') 4 | moving disk from A to B 5 | moving disk from A to C 6 | moving disk from B to C 7 | moving disk from A to B 8 | moving disk from C to A 9 | moving disk from C to B 10 | moving disk from A to B 11 | """ 12 | if height >= 1: 13 | moveTower(height - 1, fromPole, withPole, toPole) 14 | moveDisk(fromPole, toPole) 15 | moveTower(height - 1, withPole, toPole, fromPole) 16 | 17 | 18 | def moveDisk(fp, tp): 19 | print("moving disk from", fp, "to", tp) 20 | 21 | 22 | def main(): 23 | height = int(input("Height of hanoi: ").strip()) 24 | moveTower(height, "A", "B", "C") 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /project_euler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_001/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_001/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_001/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 1: https://projecteuler.net/problem=1 3 | 4 | Multiples of 3 and 5 5 | 6 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | we get 3, 5, 6 and 9. The sum of these multiples is 23. 8 | 9 | Find the sum of all the multiples of 3 or 5 below 1000. 10 | """ 11 | 12 | 13 | def solution(n: int = 1000) -> int: 14 | """ 15 | Returns the sum of all the multiples of 3 or 5 below n. 16 | 17 | >>> solution(3) 18 | 0 19 | >>> solution(4) 20 | 3 21 | >>> solution(10) 22 | 23 23 | >>> solution(600) 24 | 83700 25 | >>> solution(-7) 26 | 0 27 | """ 28 | 29 | return sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0]) 30 | 31 | 32 | if __name__ == "__main__": 33 | print(f"{solution() = }") 34 | -------------------------------------------------------------------------------- /project_euler/problem_001/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 1: https://projecteuler.net/problem=1 3 | 4 | Multiples of 3 and 5 5 | 6 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | we get 3, 5, 6 and 9. The sum of these multiples is 23. 8 | 9 | Find the sum of all the multiples of 3 or 5 below 1000. 10 | """ 11 | 12 | 13 | def solution(n: int = 1000) -> int: 14 | """ 15 | Returns the sum of all the multiples of 3 or 5 below n. 16 | 17 | >>> solution(3) 18 | 0 19 | >>> solution(4) 20 | 3 21 | >>> solution(10) 22 | 23 23 | >>> solution(600) 24 | 83700 25 | """ 26 | 27 | total = 0 28 | terms = (n - 1) // 3 29 | total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. 30 | terms = (n - 1) // 5 31 | total += ((terms) * (10 + (terms - 1) * 5)) // 2 32 | terms = (n - 1) // 15 33 | total -= ((terms) * (30 + (terms - 1) * 15)) // 2 34 | return total 35 | 36 | 37 | if __name__ == "__main__": 38 | print(f"{solution() = }") 39 | -------------------------------------------------------------------------------- /project_euler/problem_001/sol5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 1: https://projecteuler.net/problem=1 3 | 4 | Multiples of 3 and 5 5 | 6 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | we get 3, 5, 6 and 9. The sum of these multiples is 23. 8 | 9 | Find the sum of all the multiples of 3 or 5 below 1000. 10 | """ 11 | 12 | 13 | def solution(n: int = 1000) -> int: 14 | """ 15 | Returns the sum of all the multiples of 3 or 5 below n. 16 | A straightforward pythonic solution using list comprehension. 17 | 18 | >>> solution(3) 19 | 0 20 | >>> solution(4) 21 | 3 22 | >>> solution(10) 23 | 23 24 | >>> solution(600) 25 | 83700 26 | """ 27 | 28 | return sum([i for i in range(n) if i % 3 == 0 or i % 5 == 0]) 29 | 30 | 31 | if __name__ == "__main__": 32 | print(f"{solution() = }") 33 | -------------------------------------------------------------------------------- /project_euler/problem_001/sol6.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 1: https://projecteuler.net/problem=1 3 | 4 | Multiples of 3 and 5 5 | 6 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | we get 3, 5, 6 and 9. The sum of these multiples is 23. 8 | 9 | Find the sum of all the multiples of 3 or 5 below 1000. 10 | """ 11 | 12 | 13 | def solution(n: int = 1000) -> int: 14 | """ 15 | Returns the sum of all the multiples of 3 or 5 below n. 16 | 17 | >>> solution(3) 18 | 0 19 | >>> solution(4) 20 | 3 21 | >>> solution(10) 22 | 23 23 | >>> solution(600) 24 | 83700 25 | """ 26 | 27 | a = 3 28 | result = 0 29 | while a < n: 30 | if a % 3 == 0 or a % 5 == 0: 31 | result += a 32 | elif a % 15 == 0: 33 | result -= a 34 | a += 1 35 | return result 36 | 37 | 38 | if __name__ == "__main__": 39 | print(f"{solution() = }") 40 | -------------------------------------------------------------------------------- /project_euler/problem_001/sol7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 1: https://projecteuler.net/problem=1 3 | 4 | Multiples of 3 and 5 5 | 6 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | we get 3, 5, 6 and 9. The sum of these multiples is 23. 8 | 9 | Find the sum of all the multiples of 3 or 5 below 1000. 10 | """ 11 | 12 | 13 | def solution(n: int = 1000) -> int: 14 | """ 15 | Returns the sum of all the multiples of 3 or 5 below n. 16 | 17 | >>> solution(3) 18 | 0 19 | >>> solution(4) 20 | 3 21 | >>> solution(10) 22 | 23 23 | >>> solution(600) 24 | 83700 25 | """ 26 | 27 | result = 0 28 | for i in range(n): 29 | if i % 3 == 0: 30 | result += i 31 | elif i % 5 == 0: 32 | result += i 33 | return result 34 | 35 | 36 | if __name__ == "__main__": 37 | print(f"{solution() = }") 38 | -------------------------------------------------------------------------------- /project_euler/problem_002/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_002/__init__.py -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_002/sol3.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 | if n <= 1: 37 | return 0 38 | a = 0 39 | b = 2 40 | count = 0 41 | while 4 * b + a <= n: 42 | a, b = b, 4 * b + a 43 | count += a 44 | return count + b 45 | 46 | 47 | if __name__ == "__main__": 48 | print(f"{solution() = }") 49 | -------------------------------------------------------------------------------- /project_euler/problem_003/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_003/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_004/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_004/__init__.py -------------------------------------------------------------------------------- /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 × 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 | -------------------------------------------------------------------------------- /project_euler/problem_005/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_005/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_006/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_006/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_006/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 6: https://projecteuler.net/problem=6 3 | 4 | Sum square difference 5 | 6 | The sum of the squares of the first ten natural numbers is, 7 | 1^2 + 2^2 + ... + 10^2 = 385 8 | 9 | The square of the sum of the first ten natural numbers is, 10 | (1 + 2 + ... + 10)^2 = 55^2 = 3025 11 | 12 | Hence the difference between the sum of the squares of the first ten 13 | natural numbers and the square of the sum is 3025 - 385 = 2640. 14 | 15 | Find the difference between the sum of the squares of the first one 16 | hundred natural numbers and the square of the sum. 17 | """ 18 | 19 | 20 | def solution(n: int = 100) -> int: 21 | """ 22 | Returns the difference between the sum of the squares of the first n 23 | natural numbers and the square of the sum. 24 | 25 | >>> solution(10) 26 | 2640 27 | >>> solution(15) 28 | 13160 29 | >>> solution(20) 30 | 41230 31 | >>> solution(50) 32 | 1582700 33 | """ 34 | 35 | sum_cubes = (n * (n + 1) // 2) ** 2 36 | sum_squares = n * (n + 1) * (2 * n + 1) // 6 37 | return sum_cubes - sum_squares 38 | 39 | 40 | if __name__ == "__main__": 41 | print(f"{solution() = }") 42 | -------------------------------------------------------------------------------- /project_euler/problem_006/sol4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 6: https://projecteuler.net/problem=6 3 | 4 | Sum square difference 5 | 6 | The sum of the squares of the first ten natural numbers is, 7 | 1^2 + 2^2 + ... + 10^2 = 385 8 | 9 | The square of the sum of the first ten natural numbers is, 10 | (1 + 2 + ... + 10)^2 = 55^2 = 3025 11 | 12 | Hence the difference between the sum of the squares of the first ten 13 | natural numbers and the square of the sum is 3025 - 385 = 2640. 14 | 15 | Find the difference between the sum of the squares of the first one 16 | hundred natural numbers and the square of the sum. 17 | """ 18 | 19 | 20 | def solution(n: int = 100) -> int: 21 | """ 22 | Returns the difference between the sum of the squares of the first n 23 | natural numbers and the square of the sum. 24 | 25 | >>> solution(10) 26 | 2640 27 | >>> solution(15) 28 | 13160 29 | >>> solution(20) 30 | 41230 31 | >>> solution(50) 32 | 1582700 33 | """ 34 | 35 | sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 36 | square_of_sum = (n * (n + 1) / 2) ** 2 37 | return int(square_of_sum - sum_of_squares) 38 | 39 | 40 | if __name__ == "__main__": 41 | print(f"{solution() = }") 42 | -------------------------------------------------------------------------------- /project_euler/problem_007/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_007/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_008/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_008/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_009/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_009/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_009/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 9: https://projecteuler.net/problem=9 3 | 4 | Special Pythagorean triplet 5 | 6 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, 7 | 8 | a^2 + b^2 = c^2 9 | 10 | For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. 11 | 12 | There exists exactly one Pythagorean triplet for which a + b + c = 1000. 13 | Find the product a*b*c. 14 | 15 | References: 16 | - https://en.wikipedia.org/wiki/Pythagorean_triple 17 | """ 18 | 19 | 20 | def solution() -> int: 21 | """ 22 | Returns the product of a,b,c which are Pythagorean Triplet that satisfies 23 | the following: 24 | 1. a**2 + b**2 = c**2 25 | 2. a + b + c = 1000 26 | 27 | # The code below has been commented due to slow execution affecting Travis. 28 | # >>> solution() 29 | # 31875000 30 | """ 31 | 32 | return [ 33 | a * b * (1000 - a - b) 34 | for a in range(1, 999) 35 | for b in range(a, 999) 36 | if (a * a + b * b == (1000 - a - b) ** 2) 37 | ][0] 38 | 39 | 40 | if __name__ == "__main__": 41 | print(f"{solution() = }") 42 | -------------------------------------------------------------------------------- /project_euler/problem_010/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_010/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_011/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_011/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_012/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_012/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_013/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_013/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_013/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 13: https://projecteuler.net/problem=13 3 | 4 | Problem Statement: 5 | Work out the first ten digits of the sum of the following one-hundred 50-digit 6 | numbers. 7 | """ 8 | import os 9 | 10 | 11 | def solution(): 12 | """ 13 | Returns the first ten digits of the sum of the array elements 14 | from the file num.txt 15 | 16 | >>> solution() 17 | '5537376230' 18 | """ 19 | file_path = os.path.join(os.path.dirname(__file__), "num.txt") 20 | with open(file_path) as file_hand: 21 | return str(sum([int(line) for line in file_hand]))[:10] 22 | 23 | 24 | if __name__ == "__main__": 25 | print(solution()) 26 | -------------------------------------------------------------------------------- /project_euler/problem_014/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_014/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_015/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_015/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_016/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_016/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_016/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 16: https://projecteuler.net/problem=16 3 | 4 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. 5 | 6 | What is the sum of the digits of the number 2^1000? 7 | """ 8 | 9 | 10 | def solution(power: int = 1000) -> int: 11 | """Returns the sum of the digits of the number 2^power. 12 | >>> solution(1000) 13 | 1366 14 | >>> solution(50) 15 | 76 16 | >>> solution(20) 17 | 31 18 | >>> solution(15) 19 | 26 20 | """ 21 | num = 2 ** power 22 | string_num = str(num) 23 | list_num = list(string_num) 24 | sum_of_num = 0 25 | 26 | for i in list_num: 27 | sum_of_num += int(i) 28 | 29 | return sum_of_num 30 | 31 | 32 | if __name__ == "__main__": 33 | power = int(input("Enter the power of 2: ").strip()) 34 | print("2 ^ ", power, " = ", 2 ** power) 35 | result = solution(power) 36 | print("Sum of the digits is: ", result) 37 | -------------------------------------------------------------------------------- /project_euler/problem_016/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 16: https://projecteuler.net/problem=16 3 | 4 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. 5 | 6 | What is the sum of the digits of the number 2^1000? 7 | """ 8 | 9 | 10 | def solution(power: int = 1000) -> int: 11 | """Returns the sum of the digits of the number 2^power. 12 | 13 | >>> solution(1000) 14 | 1366 15 | >>> solution(50) 16 | 76 17 | >>> solution(20) 18 | 31 19 | >>> solution(15) 20 | 26 21 | """ 22 | n = 2 ** power 23 | r = 0 24 | while n: 25 | r, n = r + n % 10, n // 10 26 | return r 27 | 28 | 29 | if __name__ == "__main__": 30 | print(solution(int(str(input()).strip()))) 31 | -------------------------------------------------------------------------------- /project_euler/problem_017/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_017/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_018/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_018/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_018/triangle.txt: -------------------------------------------------------------------------------- 1 | 75 2 | 95 64 3 | 17 47 82 4 | 18 35 87 10 5 | 20 04 82 47 65 6 | 19 01 23 75 03 34 7 | 88 02 77 73 07 63 67 8 | 99 65 04 28 06 16 70 92 9 | 41 41 26 56 83 40 80 70 33 10 | 41 48 72 33 47 32 37 16 94 29 11 | 53 71 44 65 25 43 91 52 97 51 14 12 | 70 11 33 28 77 73 17 78 39 68 17 57 13 | 91 71 52 38 17 14 91 43 58 50 27 29 48 14 | 63 66 04 68 89 53 67 30 73 16 69 87 40 31 15 | 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 16 | -------------------------------------------------------------------------------- /project_euler/problem_019/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_019/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_020/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_020/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_020/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 20: https://projecteuler.net/problem=20 3 | 4 | n! means n × (n − 1) × ... × 3 × 2 × 1 5 | 6 | For example, 10! = 10 × 9 × ... × 3 × 2 × 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 | from math import factorial 12 | 13 | 14 | def solution(num: int = 100) -> int: 15 | """Returns the sum of the digits in the factorial of num 16 | >>> solution(100) 17 | 648 18 | >>> solution(50) 19 | 216 20 | >>> solution(10) 21 | 27 22 | >>> solution(5) 23 | 3 24 | >>> solution(3) 25 | 6 26 | >>> solution(2) 27 | 2 28 | >>> solution(1) 29 | 1 30 | """ 31 | return sum([int(x) for x in str(factorial(num))]) 32 | 33 | 34 | if __name__ == "__main__": 35 | print(solution(int(input("Enter the Number: ").strip()))) 36 | -------------------------------------------------------------------------------- /project_euler/problem_020/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 20: https://projecteuler.net/problem=20 3 | 4 | n! means n × (n − 1) × ... × 3 × 2 × 1 5 | 6 | For example, 10! = 10 × 9 × ... × 3 × 2 × 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 | from math import factorial 12 | 13 | 14 | def solution(num: int = 100) -> int: 15 | """Returns the sum of the digits in the factorial of num 16 | >>> solution(1000) 17 | 10539 18 | >>> solution(200) 19 | 1404 20 | >>> solution(100) 21 | 648 22 | >>> solution(50) 23 | 216 24 | >>> solution(10) 25 | 27 26 | >>> solution(5) 27 | 3 28 | >>> solution(3) 29 | 6 30 | >>> solution(2) 31 | 2 32 | >>> solution(1) 33 | 1 34 | >>> solution(0) 35 | 1 36 | """ 37 | return sum(map(int, str(factorial(num)))) 38 | 39 | 40 | if __name__ == "__main__": 41 | print(solution(int(input("Enter the Number: ").strip()))) 42 | -------------------------------------------------------------------------------- /project_euler/problem_020/sol4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 20: https://projecteuler.net/problem=20 3 | 4 | n! means n × (n − 1) × ... × 3 × 2 × 1 5 | 6 | For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, 7 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 8 | 9 | Find the sum of the digits in the number 100! 10 | """ 11 | 12 | 13 | def solution(num: int = 100) -> int: 14 | """Returns the sum of the digits in the factorial of num 15 | >>> solution(100) 16 | 648 17 | >>> solution(50) 18 | 216 19 | >>> solution(10) 20 | 27 21 | >>> solution(5) 22 | 3 23 | >>> solution(3) 24 | 6 25 | >>> solution(2) 26 | 2 27 | >>> solution(1) 28 | 1 29 | """ 30 | fact = 1 31 | result = 0 32 | for i in range(1, num + 1): 33 | fact *= i 34 | 35 | for j in str(fact): 36 | result += int(j) 37 | 38 | return result 39 | 40 | 41 | if __name__ == "__main__": 42 | print(solution(int(input("Enter the Number: ").strip()))) 43 | -------------------------------------------------------------------------------- /project_euler/problem_021/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_021/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_022/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_022/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_023/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_023/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_024/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_024/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_024/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | A permutation is an ordered arrangement of objects. For example, 3124 is one 3 | possible permutation of the digits 1, 2, 3 and 4. If all of the permutations 4 | are listed numerically or alphabetically, we call it lexicographic order. The 5 | lexicographic permutations of 0, 1 and 2 are: 6 | 7 | 012 021 102 120 201 210 8 | 9 | What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 10 | 6, 7, 8 and 9? 11 | """ 12 | from itertools import permutations 13 | 14 | 15 | def solution(): 16 | """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 17 | 3, 4, 5, 6, 7, 8 and 9. 18 | 19 | >>> solution() 20 | '2783915460' 21 | """ 22 | result = list(map("".join, permutations("0123456789"))) 23 | return result[999999] 24 | 25 | 26 | if __name__ == "__main__": 27 | print(solution()) 28 | -------------------------------------------------------------------------------- /project_euler/problem_025/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_025/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_026/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_026/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_027/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_027/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_028/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_028/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_029/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_029/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_030/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_030/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_031/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_031/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_032/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_032/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_033/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_033/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_034/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /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 | 12 | def sum_of_digit_factorial(n: int) -> int: 13 | """ 14 | Returns the sum of the digits in n 15 | >>> sum_of_digit_factorial(15) 16 | 121 17 | >>> sum_of_digit_factorial(0) 18 | 1 19 | """ 20 | return sum(factorial(int(char)) for char in str(n)) 21 | 22 | 23 | def solution() -> int: 24 | """ 25 | Returns the sum of all numbers whose 26 | sum of the factorials of all digits 27 | add up to the number itself. 28 | >>> solution() 29 | 40730 30 | """ 31 | limit = 7 * factorial(9) + 1 32 | return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i) 33 | 34 | 35 | if __name__ == "__main__": 36 | print(f"{solution()} = ") 37 | -------------------------------------------------------------------------------- /project_euler/problem_035/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_036/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_036/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_037/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_038/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_038/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_039/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_040/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_040/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_040/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Champernowne's constant 3 | Problem 40 4 | An irrational decimal fraction is created by concatenating the positive 5 | integers: 6 | 7 | 0.123456789101112131415161718192021... 8 | 9 | It can be seen that the 12th digit of the fractional part is 1. 10 | 11 | If dn represents the nth digit of the fractional part, find the value of the 12 | following expression. 13 | 14 | d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 15 | """ 16 | 17 | 18 | def solution(): 19 | """Returns 20 | 21 | >>> solution() 22 | 210 23 | """ 24 | constant = [] 25 | i = 1 26 | 27 | while len(constant) < 1e6: 28 | constant.append(str(i)) 29 | i += 1 30 | 31 | constant = "".join(constant) 32 | 33 | return ( 34 | int(constant[0]) 35 | * int(constant[9]) 36 | * int(constant[99]) 37 | * int(constant[999]) 38 | * int(constant[9999]) 39 | * int(constant[99999]) 40 | * int(constant[999999]) 41 | ) 42 | 43 | 44 | if __name__ == "__main__": 45 | print(solution()) 46 | -------------------------------------------------------------------------------- /project_euler/problem_041/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_042/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_042/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_043/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_044/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_045/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_046/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_047/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_047/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_048/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_048/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_048/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Self Powers 3 | Problem 48 4 | 5 | The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. 6 | 7 | Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. 8 | """ 9 | 10 | 11 | def solution(): 12 | """ 13 | Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. 14 | 15 | >>> solution() 16 | '9110846700' 17 | """ 18 | total = 0 19 | for i in range(1, 1001): 20 | total += i ** i 21 | return str(total)[-10:] 22 | 23 | 24 | if __name__ == "__main__": 25 | print(solution()) 26 | -------------------------------------------------------------------------------- /project_euler/problem_049/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_049/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_050/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_050/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_051/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_051/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_052/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_052/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_052/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Permuted multiples 3 | Problem 52 4 | 5 | It can be seen that the number, 125874, and its double, 251748, contain exactly 6 | the same digits, but in a different order. 7 | 8 | Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, 9 | contain the same digits. 10 | """ 11 | 12 | 13 | def solution(): 14 | """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 15 | 6x, contain the same digits. 16 | 17 | >>> solution() 18 | 142857 19 | """ 20 | i = 1 21 | 22 | while True: 23 | if ( 24 | sorted(list(str(i))) 25 | == sorted(list(str(2 * i))) 26 | == sorted(list(str(3 * i))) 27 | == sorted(list(str(4 * i))) 28 | == sorted(list(str(5 * i))) 29 | == sorted(list(str(6 * i))) 30 | ): 31 | return i 32 | 33 | i += 1 34 | 35 | 36 | if __name__ == "__main__": 37 | print(solution()) 38 | -------------------------------------------------------------------------------- /project_euler/problem_053/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_053/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_053/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Combinatoric selections 3 | Problem 53 4 | 5 | There are exactly ten ways of selecting three from five, 12345: 6 | 7 | 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 8 | 9 | In combinatorics, we use the notation, 5C3 = 10. 10 | 11 | In general, 12 | 13 | nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1. 14 | It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. 15 | 16 | How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater 17 | than one-million? 18 | """ 19 | from math import factorial 20 | 21 | 22 | def combinations(n, r): 23 | return factorial(n) / (factorial(r) * factorial(n - r)) 24 | 25 | 26 | def solution(): 27 | """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than 28 | one-million 29 | 30 | >>> solution() 31 | 4075 32 | """ 33 | total = 0 34 | 35 | for i in range(1, 101): 36 | for j in range(1, i + 1): 37 | if combinations(i, j) > 1e6: 38 | total += 1 39 | return total 40 | 41 | 42 | if __name__ == "__main__": 43 | print(solution()) 44 | -------------------------------------------------------------------------------- /project_euler/problem_054/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_054/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_055/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_056/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_056/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_057/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_057/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_058/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_062/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_062/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_063/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_063/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 3 | 134217728=89, is a ninth power. 4 | How many n-digit positive integers exist which are also an nth power? 5 | """ 6 | 7 | """ 8 | The maximum base can be 9 because all n-digit numbers < 10^n. 9 | Now 9**23 has 22 digits so the maximum power can be 22. 10 | Using these conclusions, we will calculate the result. 11 | """ 12 | 13 | 14 | def solution(max_base: int = 10, max_power: int = 22) -> int: 15 | """ 16 | Returns the count of all n-digit numbers which are nth power 17 | >>> solution(10, 22) 18 | 49 19 | >>> solution(0, 0) 20 | 0 21 | >>> solution(1, 1) 22 | 0 23 | >>> solution(-1, -1) 24 | 0 25 | """ 26 | bases = range(1, max_base) 27 | powers = range(1, max_power) 28 | return sum( 29 | 1 for power in powers for base in bases if len(str(base ** power)) == power 30 | ) 31 | 32 | 33 | if __name__ == "__main__": 34 | print(f"{solution(10, 22) = }") 35 | -------------------------------------------------------------------------------- /project_euler/problem_064/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_064/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_065/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_065/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_067/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_067/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_069/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_069/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_070/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_070/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_071/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_071/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_072/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_072/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_074/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_074/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_075/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_075/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_076/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_076/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_077/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_077/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_080/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_080/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_080/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 80: https://projecteuler.net/problem=80 3 | Author: Sandeep Gupta 4 | Problem statement: For the first one hundred natural numbers, find the total of 5 | the digital sums of the first one hundred decimal digits for all the irrational 6 | square roots. 7 | Time: 5 October 2020, 18:30 8 | """ 9 | import decimal 10 | 11 | 12 | def solution() -> int: 13 | """ 14 | To evaluate the sum, Used decimal python module to calculate the decimal 15 | places up to 100, the most important thing would be take calculate 16 | a few extra places for decimal otherwise there will be rounding 17 | error. 18 | 19 | >>> solution() 20 | 40886 21 | """ 22 | answer = 0 23 | decimal_context = decimal.Context(prec=105) 24 | for i in range(2, 100): 25 | number = decimal.Decimal(i) 26 | sqrt_number = number.sqrt(decimal_context) 27 | if len(str(sqrt_number)) > 1: 28 | answer += int(str(sqrt_number)[0]) 29 | sqrt_number = str(sqrt_number)[2:101] 30 | answer += sum([int(x) for x in sqrt_number]) 31 | return answer 32 | 33 | 34 | if __name__ == "__main__": 35 | import doctest 36 | 37 | doctest.testmod() 38 | -------------------------------------------------------------------------------- /project_euler/problem_081/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_081/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_087/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_087/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_089/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_089/numeralcleanup_test.txt: -------------------------------------------------------------------------------- 1 | IIII 2 | IV 3 | IIIIIIIIII 4 | X 5 | VIIIII 6 | -------------------------------------------------------------------------------- /project_euler/problem_091/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_091/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_097/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_099/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_099/__init__.py -------------------------------------------------------------------------------- /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 = [0, 0] 26 | for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))): 27 | a, x = list(map(int, line.split(","))) 28 | if x * log10(a) > largest[0]: 29 | largest = [x * log10(a), i + 1] 30 | return largest[1] 31 | 32 | 33 | if __name__ == "__main__": 34 | print(solution()) 35 | -------------------------------------------------------------------------------- /project_euler/problem_112/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_112/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_113/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_113/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_119/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_119/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_120/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_120/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_120/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 120 Square remainders: https://projecteuler.net/problem=120 3 | 4 | Description: 5 | 6 | Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2. 7 | For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49. 8 | And as n varies, so too will r, but for a = 7 it turns out that r_max = 42. 9 | For 3 ≤ a ≤ 1000, find ∑ r_max. 10 | 11 | Solution: 12 | 13 | On expanding the terms, we get 2 if n is even and 2an if n is odd. 14 | For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division) 15 | """ 16 | 17 | 18 | def solution(n: int = 1000) -> int: 19 | """ 20 | Returns ∑ r_max for 3 <= a <= n as explained above 21 | >>> solution(10) 22 | 300 23 | >>> solution(100) 24 | 330750 25 | >>> solution(1000) 26 | 333082500 27 | """ 28 | return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1)) 29 | 30 | 31 | if __name__ == "__main__": 32 | print(solution()) 33 | -------------------------------------------------------------------------------- /project_euler/problem_123/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_123/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_125/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_125/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_129/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_129/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_173/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_173/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_174/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_174/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_188/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_188/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_191/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_191/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_203/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_203/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_206/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_206/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_207/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_207/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_234/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_234/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_301/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_301/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_551/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/project_euler/problem_551/__init__.py -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | # Setup for pytest 2 | [pytest] 3 | markers = 4 | mat_ops: mark a test as utilizing matrix operations. 5 | addopts = --durations=10 6 | -------------------------------------------------------------------------------- /quantum/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Quantum Algorithms 2 | 3 | Started at https://github.com/TheAlgorithms/Python/issues/1831 4 | 5 | * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems 6 | * Google: https://research.google/teams/applied-science/quantum 7 | * IBM: https://qiskit.org and https://github.com/Qiskit 8 | * Rigetti: https://rigetti.com and https://github.com/rigetti 9 | 10 | ## IBM Qiskit 11 | - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. 12 | - Tutorials & References 13 | - https://github.com/Qiskit/qiskit-tutorials 14 | - https://quantum-computing.ibm.com/docs/iql/first-circuit 15 | - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02 16 | -------------------------------------------------------------------------------- /quantum/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/quantum/__init__.py -------------------------------------------------------------------------------- /quantum/single_qubit_measure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Build a simple bare-minimum quantum circuit that starts with a single 4 | qubit (by default, in state 0), runs the experiment 1000 times, and 5 | finally prints the total count of the states finally observed. 6 | Qiskit Docs: https://qiskit.org/documentation/getting_started.html 7 | """ 8 | 9 | import qiskit as q 10 | 11 | 12 | def single_qubit_measure(qubits: int, classical_bits: int) -> q.result.counts.Counts: 13 | """ 14 | >>> single_qubit_measure(1, 1) 15 | {'0': 1000} 16 | """ 17 | # Use Aer's qasm_simulator 18 | simulator = q.Aer.get_backend("qasm_simulator") 19 | 20 | # Create a Quantum Circuit acting on the q register 21 | circuit = q.QuantumCircuit(qubits, classical_bits) 22 | 23 | # Map the quantum measurement to the classical bits 24 | circuit.measure([0], [0]) 25 | 26 | # Execute the circuit on the qasm simulator 27 | job = q.execute(circuit, simulator, shots=1000) 28 | 29 | # Return the histogram data of the results of the experiment. 30 | return job.result().get_counts(circuit) 31 | 32 | 33 | if __name__ == "__main__": 34 | print(f"Total count for various states are: {single_qubit_measure(1, 1)}") 35 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | fake_useragent 3 | keras; python_version < '3.9' 4 | lxml 5 | matplotlib 6 | numpy 7 | opencv-python 8 | pandas 9 | pillow 10 | qiskit 11 | requests 12 | scikit-fuzzy 13 | sklearn 14 | statsmodels 15 | sympy 16 | tensorflow; python_version < '3.9' 17 | xgboost 18 | -------------------------------------------------------------------------------- /scheduling/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/scheduling/__init__.py -------------------------------------------------------------------------------- /scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/scripts/__init__.py -------------------------------------------------------------------------------- /searches/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/searches/__init__.py -------------------------------------------------------------------------------- /searches/double_linear_search_recursion.py: -------------------------------------------------------------------------------- 1 | def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: 2 | """ 3 | Iterate through the array to find the index of key using recursion. 4 | :param list_data: the list to be searched 5 | :param key: the key to be searched 6 | :param left: the index of first element 7 | :param right: the index of last element 8 | :return: the index of key value if found, -1 otherwise. 9 | 10 | >>> search(list(range(0, 11)), 5) 11 | 5 12 | >>> search([1, 2, 4, 5, 3], 4) 13 | 2 14 | >>> search([1, 2, 4, 5, 3], 6) 15 | -1 16 | >>> search([5], 5) 17 | 0 18 | >>> search([], 1) 19 | -1 20 | """ 21 | right = right or len(list_data) - 1 22 | if left > right: 23 | return -1 24 | elif list_data[left] == key: 25 | return left 26 | elif list_data[right] == key: 27 | return right 28 | else: 29 | return search(list_data, key, left + 1, right - 1) 30 | 31 | 32 | if __name__ == "__main__": 33 | import doctest 34 | 35 | doctest.testmod() 36 | -------------------------------------------------------------------------------- /searches/tabu_test_data.txt: -------------------------------------------------------------------------------- 1 | a b 20 2 | a c 18 3 | a d 22 4 | a e 26 5 | b c 10 6 | b d 11 7 | b e 12 8 | c d 23 9 | c e 24 10 | d e 40 11 | -------------------------------------------------------------------------------- /sorts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/sorts/__init__.py -------------------------------------------------------------------------------- /sorts/odd_even_transposition_single_threaded.py: -------------------------------------------------------------------------------- 1 | """ 2 | Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort 3 | 4 | This is a non-parallelized implementation of odd-even transpostiion sort. 5 | 6 | Normally the swaps in each set happen simultaneously, without that the algorithm 7 | is no better than bubble sort. 8 | """ 9 | 10 | 11 | def odd_even_transposition(arr: list) -> list: 12 | """ 13 | >>> odd_even_transposition([5, 4, 3, 2, 1]) 14 | [1, 2, 3, 4, 5] 15 | 16 | >>> odd_even_transposition([13, 11, 18, 0, -1]) 17 | [-1, 0, 11, 13, 18] 18 | 19 | >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) 20 | [-2.9, -0.1, 0.1, 1.1] 21 | """ 22 | arr_size = len(arr) 23 | for _ in range(arr_size): 24 | for i in range(_ % 2, arr_size - 1, 2): 25 | if arr[i + 1] < arr[i]: 26 | arr[i], arr[i + 1] = arr[i + 1], arr[i] 27 | 28 | return arr 29 | 30 | 31 | if __name__ == "__main__": 32 | arr = list(range(10, 0, -1)) 33 | print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}") 34 | -------------------------------------------------------------------------------- /sorts/recursive_quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(data: list) -> list: 2 | """ 3 | >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): 4 | ... quick_sort(data) == sorted(data) 5 | True 6 | True 7 | True 8 | """ 9 | if len(data) <= 1: 10 | return data 11 | else: 12 | return ( 13 | quick_sort([e for e in data[1:] if e <= data[0]]) 14 | + [data[0]] 15 | + quick_sort([e for e in data[1:] if e > data[0]]) 16 | ) 17 | 18 | 19 | if __name__ == "__main__": 20 | import doctest 21 | 22 | doctest.testmod() 23 | -------------------------------------------------------------------------------- /sorts/stooge_sort.py: -------------------------------------------------------------------------------- 1 | def stooge_sort(arr): 2 | """ 3 | Examples: 4 | >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) 5 | [-7.1, -1, 0, 2, 2, 18.1] 6 | 7 | >>> stooge_sort([]) 8 | [] 9 | """ 10 | stooge(arr, 0, len(arr) - 1) 11 | return arr 12 | 13 | 14 | def stooge(arr, i, h): 15 | 16 | if i >= h: 17 | return 18 | 19 | # If first element is smaller than the last then swap them 20 | if arr[i] > arr[h]: 21 | arr[i], arr[h] = arr[h], arr[i] 22 | 23 | # If there are more than 2 elements in the array 24 | if h - i + 1 > 2: 25 | t = (int)((h - i + 1) / 3) 26 | 27 | # Recursively sort first 2/3 elements 28 | stooge(arr, i, (h - t)) 29 | 30 | # Recursively sort last 2/3 elements 31 | stooge(arr, i + t, (h)) 32 | 33 | # Recursively sort first 2/3 elements 34 | stooge(arr, i, (h - t)) 35 | 36 | 37 | if __name__ == "__main__": 38 | user_input = input("Enter numbers separated by a comma:\n").strip() 39 | unsorted = [int(item) for item in user_input.split(",")] 40 | print(stooge_sort(unsorted)) 41 | -------------------------------------------------------------------------------- /sorts/topological_sort.py: -------------------------------------------------------------------------------- 1 | """Topological Sort.""" 2 | 3 | # a 4 | # / \ 5 | # b c 6 | # / \ 7 | # d e 8 | edges = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} 9 | vertices = ["a", "b", "c", "d", "e"] 10 | 11 | 12 | def topological_sort(start, visited, sort): 13 | """Perform topolical sort on a directed acyclic graph.""" 14 | current = start 15 | # add current to visited 16 | visited.append(current) 17 | neighbors = edges[current] 18 | for neighbor in neighbors: 19 | # if neighbor not in visited, visit 20 | if neighbor not in visited: 21 | sort = topological_sort(neighbor, visited, sort) 22 | # if all neighbors visited add current to sort 23 | sort.append(current) 24 | # if all vertices haven't been visited select a new one to visit 25 | if len(visited) != len(vertices): 26 | for vertice in vertices: 27 | if vertice not in visited: 28 | sort = topological_sort(vertice, visited, sort) 29 | # return sort 30 | return sort 31 | 32 | 33 | if __name__ == "__main__": 34 | sort = topological_sort("a", [], []) 35 | print(sort) 36 | -------------------------------------------------------------------------------- /sorts/wiggle_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wiggle Sort. 3 | 4 | Given an unsorted array nums, reorder it such 5 | that nums[0] < nums[1] > nums[2] < nums[3].... 6 | For example: 7 | if input numbers = [3, 5, 2, 1, 6, 4] 8 | one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. 9 | """ 10 | 11 | 12 | def wiggle_sort(nums: list) -> list: 13 | """ 14 | Python implementation of wiggle. 15 | Example: 16 | >>> wiggle_sort([0, 5, 3, 2, 2]) 17 | [0, 5, 2, 3, 2] 18 | >>> wiggle_sort([]) 19 | [] 20 | >>> wiggle_sort([-2, -5, -45]) 21 | [-45, -2, -5] 22 | >>> wiggle_sort([-2.1, -5.68, -45.11]) 23 | [-45.11, -2.1, -5.68] 24 | """ 25 | for i, _ in enumerate(nums): 26 | if (i % 2 == 1) == (nums[i - 1] > nums[i]): 27 | nums[i - 1], nums[i] = nums[i], nums[i - 1] 28 | 29 | return nums 30 | 31 | 32 | if __name__ == "__main__": 33 | print("Enter the array elements:") 34 | array = list(map(int, input().split())) 35 | print("The unsorted array is:") 36 | print(array) 37 | print("Array after Wiggle sort:") 38 | print(wiggle_sort(array)) 39 | -------------------------------------------------------------------------------- /strings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/strings/__init__.py -------------------------------------------------------------------------------- /strings/capitalize.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase, ascii_uppercase 2 | 3 | 4 | def capitalize(sentence: str) -> str: 5 | """ 6 | This function will capitalize the first letter of a sentence or a word 7 | >>> capitalize("hello world") 8 | 'Hello world' 9 | >>> capitalize("123 hello world") 10 | '123 hello world' 11 | >>> capitalize(" hello world") 12 | ' hello world' 13 | >>> capitalize("a") 14 | 'A' 15 | >>> capitalize("") 16 | '' 17 | """ 18 | if not sentence: 19 | return "" 20 | lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} 21 | return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] 22 | 23 | 24 | if __name__ == "__main__": 25 | from doctest import testmod 26 | 27 | testmod() 28 | -------------------------------------------------------------------------------- /strings/check_anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | wiki: https://en.wikipedia.org/wiki/Anagram 3 | """ 4 | 5 | 6 | def check_anagrams(first_str: str, second_str: str) -> bool: 7 | """ 8 | Two strings are anagrams if they are made of the same letters 9 | arranged differently (ignoring the case). 10 | >>> check_anagrams('Silent', 'Listen') 11 | True 12 | >>> check_anagrams('This is a string', 'Is this a string') 13 | True 14 | >>> check_anagrams('This is a string', 'Is this a string') 15 | True 16 | >>> check_anagrams('There', 'Their') 17 | False 18 | """ 19 | return ( 20 | "".join(sorted(first_str.lower())).strip() 21 | == "".join(sorted(second_str.lower())).strip() 22 | ) 23 | 24 | 25 | if __name__ == "__main__": 26 | from doctest import testmod 27 | 28 | testmod() 29 | input_A = input("Enter the first string ").strip() 30 | input_B = input("Enter the second string ").strip() 31 | 32 | status = check_anagrams(input_A, input_B) 33 | print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.") 34 | -------------------------------------------------------------------------------- /strings/is_palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s: str) -> bool: 2 | """ 3 | Determine whether the string is palindrome 4 | :param s: 5 | :return: Boolean 6 | >>> is_palindrome("a man a plan a canal panama".replace(" ", "")) 7 | True 8 | >>> is_palindrome("Hello") 9 | False 10 | >>> is_palindrome("Able was I ere I saw Elba") 11 | True 12 | >>> is_palindrome("racecar") 13 | True 14 | >>> is_palindrome("Mr. Owl ate my metal worm?") 15 | True 16 | """ 17 | # Since Punctuation, capitalization, and spaces are usually ignored while checking 18 | # Palindrome, we first remove them from our string. 19 | s = "".join([character for character in s.lower() if character.isalnum()]) 20 | return s == s[::-1] 21 | 22 | 23 | if __name__ == "__main__": 24 | s = input("Enter string to determine whether its palindrome or not: ").strip() 25 | if is_palindrome(s): 26 | print("Given string is palindrome") 27 | else: 28 | print("Given string is not palindrome") 29 | -------------------------------------------------------------------------------- /strings/lower.py: -------------------------------------------------------------------------------- 1 | def lower(word: str) -> str: 2 | """ 3 | Will convert the entire string to lowecase letters 4 | 5 | >>> lower("wow") 6 | 'wow' 7 | >>> lower("HellZo") 8 | 'hellzo' 9 | >>> lower("WHAT") 10 | 'what' 11 | >>> lower("wh[]32") 12 | 'wh[]32' 13 | >>> lower("whAT") 14 | 'what' 15 | """ 16 | 17 | # converting to ascii value int value and checking to see if char is a capital 18 | # letter if it is a capital letter it is getting shift by 32 which makes it a lower 19 | # case letter 20 | return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) 21 | 22 | 23 | if __name__ == "__main__": 24 | from doctest import testmod 25 | 26 | testmod() 27 | -------------------------------------------------------------------------------- /strings/remove_duplicate.py: -------------------------------------------------------------------------------- 1 | def remove_duplicates(sentence: str) -> str: 2 | """ 3 | Remove duplicates from sentence 4 | >>> remove_duplicates("Python is great and Java is also great") 5 | 'Java Python also and great is' 6 | >>> remove_duplicates("Python is great and Java is also great") 7 | 'Java Python also and great is' 8 | """ 9 | return " ".join(sorted(set(sentence.split()))) 10 | 11 | 12 | if __name__ == "__main__": 13 | import doctest 14 | 15 | doctest.testmod() 16 | -------------------------------------------------------------------------------- /strings/reverse_letters.py: -------------------------------------------------------------------------------- 1 | def reverse_letters(input_str: str) -> str: 2 | """ 3 | Reverses letters in a given string without adjusting the position of the words 4 | >>> reverse_letters('The cat in the hat') 5 | 'ehT tac ni eht tah' 6 | >>> reverse_letters('The quick brown fox jumped over the lazy dog.') 7 | 'ehT kciuq nworb xof depmuj revo eht yzal .god' 8 | >>> reverse_letters('Is this true?') 9 | 'sI siht ?eurt' 10 | >>> reverse_letters("I love Python") 11 | 'I evol nohtyP' 12 | """ 13 | return " ".join([word[::-1] for word in input_str.split()]) 14 | 15 | 16 | if __name__ == "__main__": 17 | import doctest 18 | 19 | doctest.testmod() 20 | -------------------------------------------------------------------------------- /strings/reverse_words.py: -------------------------------------------------------------------------------- 1 | def reverse_words(input_str: str) -> str: 2 | """ 3 | Reverses words in a given string 4 | >>> reverse_words("I love Python") 5 | 'Python love I' 6 | >>> reverse_words("I Love Python") 7 | 'Python Love I' 8 | """ 9 | return " ".join(input_str.split()[::-1]) 10 | 11 | 12 | if __name__ == "__main__": 13 | import doctest 14 | 15 | doctest.testmod() 16 | -------------------------------------------------------------------------------- /strings/split.py: -------------------------------------------------------------------------------- 1 | def split(string: str, separator: str = " ") -> list: 2 | """ 3 | Will split the string up into all the values separated by the separator 4 | (defaults to spaces) 5 | 6 | >>> split("apple#banana#cherry#orange",separator='#') 7 | ['apple', 'banana', 'cherry', 'orange'] 8 | 9 | >>> split("Hello there") 10 | ['Hello', 'there'] 11 | 12 | >>> split("11/22/63",separator = '/') 13 | ['11', '22', '63'] 14 | 15 | >>> split("12:43:39",separator = ":") 16 | ['12', '43', '39'] 17 | """ 18 | 19 | split_words = [] 20 | 21 | last_index = 0 22 | for index, char in enumerate(string): 23 | if char == separator: 24 | split_words.append(string[last_index:index]) 25 | last_index = index + 1 26 | elif index + 1 == len(string): 27 | split_words.append(string[last_index : index + 1]) 28 | return split_words 29 | 30 | 31 | if __name__ == "__main__": 32 | from doctest import testmod 33 | 34 | testmod() 35 | -------------------------------------------------------------------------------- /strings/swap_case.py: -------------------------------------------------------------------------------- 1 | """ 2 | This algorithm helps you to swap cases. 3 | 4 | User will give input and then program will perform swap cases. 5 | 6 | In other words, convert all lowercase letters to uppercase letters and vice versa. 7 | For example: 8 | 1. Please input sentence: Algorithm.Python@89 9 | aLGORITHM.pYTHON@89 10 | 2. Please input sentence: github.com/mayur200 11 | GITHUB.COM/MAYUR200 12 | 13 | """ 14 | 15 | 16 | def swap_case(sentence: str) -> str: 17 | """ 18 | This function will convert all lowercase letters to uppercase letters 19 | and vice versa. 20 | 21 | >>> swap_case('Algorithm.Python@89') 22 | 'aLGORITHM.pYTHON@89' 23 | """ 24 | new_string = "" 25 | for char in sentence: 26 | if char.isupper(): 27 | new_string += char.lower() 28 | elif char.islower(): 29 | new_string += char.upper() 30 | else: 31 | new_string += char 32 | 33 | return new_string 34 | 35 | 36 | if __name__ == "__main__": 37 | print(swap_case(input("Please input sentence: "))) 38 | -------------------------------------------------------------------------------- /strings/upper.py: -------------------------------------------------------------------------------- 1 | def upper(word: str) -> str: 2 | """ 3 | Will convert the entire string to uppercase letters 4 | 5 | >>> upper("wow") 6 | 'WOW' 7 | >>> upper("Hello") 8 | 'HELLO' 9 | >>> upper("WHAT") 10 | 'WHAT' 11 | >>> upper("wh[]32") 12 | 'WH[]32' 13 | """ 14 | 15 | # Converting to ascii value int value and checking to see if char is a lower letter 16 | # if it is a lowercase letter it is getting shift by 32 which makes it an uppercase 17 | # case letter 18 | return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) 19 | 20 | 21 | if __name__ == "__main__": 22 | from doctest import testmod 23 | 24 | testmod() 25 | -------------------------------------------------------------------------------- /strings/word_occurrence.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 17/11/19 2 | # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 3 | from collections import defaultdict 4 | 5 | 6 | def word_occurence(sentence: str) -> dict: 7 | """ 8 | >>> from collections import Counter 9 | >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" 10 | >>> occurence_dict = word_occurence(SENTENCE) 11 | >>> all(occurence_dict[word] == count for word, count 12 | ... in Counter(SENTENCE.split()).items()) 13 | True 14 | >>> dict(word_occurence("Two spaces")) 15 | {'Two': 1, 'spaces': 1} 16 | """ 17 | occurrence = defaultdict(int) 18 | # Creating a dictionary containing count of each word 19 | for word in sentence.split(): 20 | occurrence[word] += 1 21 | return occurrence 22 | 23 | 24 | if __name__ == "__main__": 25 | for word, count in word_occurence("INPUT STRING").items(): 26 | print(f"{word}: {count}") 27 | -------------------------------------------------------------------------------- /traversals/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/traversals/__init__.py -------------------------------------------------------------------------------- /web_programming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kushal997-das/Python-1/1e1708b8a1644d994ad004cc6fe20893a328519c/web_programming/__init__.py -------------------------------------------------------------------------------- /web_programming/co2_emission.py: -------------------------------------------------------------------------------- 1 | """ 2 | Get CO2 emission data from the UK CarbonIntensity API 3 | """ 4 | from datetime import date 5 | 6 | import requests 7 | 8 | BASE_URL = "https://api.carbonintensity.org.uk/intensity" 9 | 10 | 11 | # Emission in the last half hour 12 | def fetch_last_half_hour() -> str: 13 | last_half_hour = requests.get(BASE_URL).json()["data"][0] 14 | return last_half_hour["intensity"]["actual"] 15 | 16 | 17 | # Emissions in a specific date range 18 | def fetch_from_to(start, end) -> list: 19 | return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"] 20 | 21 | 22 | if __name__ == "__main__": 23 | for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)): 24 | print("from {from} to {to}: {intensity[actual]}".format(**entry)) 25 | print(f"{fetch_last_half_hour() = }") 26 | -------------------------------------------------------------------------------- /web_programming/covid_stats_via_xpath.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is to show simple COVID19 info fetching from worldometers site using lxml 3 | * The main motivation to use lxml in place of bs4 is that it is faster and therefore 4 | more convenient to use in Python web projects (e.g. Django or Flask-based) 5 | """ 6 | 7 | from collections import namedtuple 8 | 9 | import requests 10 | from lxml import html 11 | 12 | covid_data = namedtuple("covid_data", "cases deaths recovered") 13 | 14 | 15 | def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data: 16 | xpath_str = '//div[@class = "maincounter-number"]/span/text()' 17 | return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str)) 18 | 19 | 20 | fmt = """Total COVID-19 cases in the world: {} 21 | Total deaths due to COVID-19 in the world: {} 22 | Total COVID-19 patients recovered in the world: {}""" 23 | print(fmt.format(*covid_stats())) 24 | -------------------------------------------------------------------------------- /web_programming/crawl_google_results.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import webbrowser 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | from fake_useragent import UserAgent 7 | 8 | if __name__ == "__main__": 9 | print("Googling.....") 10 | url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) 11 | res = requests.get(url, headers={"UserAgent": UserAgent().random}) 12 | # res.raise_for_status() 13 | with open("project1a.html", "wb") as out_file: # only for knowing the class 14 | for data in res.iter_content(10000): 15 | out_file.write(data) 16 | soup = BeautifulSoup(res.text, "html.parser") 17 | links = list(soup.select(".eZt8xd"))[:5] 18 | 19 | print(len(links)) 20 | for link in links: 21 | if link.text == "Maps": 22 | webbrowser.open(link.get("href")) 23 | else: 24 | webbrowser.open(f"http://google.com{link.get('href')}") 25 | -------------------------------------------------------------------------------- /web_programming/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(requests.get(base_url, params=params).content, "html.parser") 15 | div = soup.find("div", attrs={"class": "gs_ri"}) 16 | anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") 17 | return anchors[2].get_text() 18 | 19 | 20 | if __name__ == "__main__": 21 | params = { 22 | "title": ( 23 | "Precisely geometry controlled microsupercapacitors for ultrahigh areal " 24 | "capacitance, volumetric capacitance, and energy density" 25 | ), 26 | "journal": "Chem. Mater.", 27 | "volume": 30, 28 | "pages": "3979-3990", 29 | "year": 2018, 30 | "hl": "en", 31 | } 32 | print(get_citation("http://scholar.google.com/scholar_lookup", params=params)) 33 | -------------------------------------------------------------------------------- /web_programming/current_stock_price.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def stock_price(symbol: str = "AAPL") -> str: 6 | url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" 7 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 8 | class_ = "My(6px) Pos(r) smartphone_Mt(6px)" 9 | return soup.find("div", class_=class_).find("span").text 10 | 11 | 12 | if __name__ == "__main__": 13 | for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): 14 | print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}") 15 | -------------------------------------------------------------------------------- /web_programming/current_weather.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | APPID = "" # <-- Put your OpenWeatherMap appid here! 4 | URL_BASE = "http://api.openweathermap.org/data/2.5/" 5 | 6 | 7 | def current_weather(q: str = "Chicago", appid: str = APPID) -> dict: 8 | """https://openweathermap.org/api""" 9 | return requests.get(URL_BASE + "weather", params=locals()).json() 10 | 11 | 12 | def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict: 13 | """https://openweathermap.org/forecast5""" 14 | return requests.get(URL_BASE + "forecast", params=locals()).json() 15 | 16 | 17 | def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict: 18 | """https://openweathermap.org/api/one-call-api""" 19 | return requests.get(URL_BASE + "onecall", params=locals()).json() 20 | 21 | 22 | if __name__ == "__main__": 23 | from pprint import pprint 24 | 25 | while True: 26 | location = input("Enter a location:").strip() 27 | if location: 28 | pprint(current_weather(location)) 29 | else: 30 | break 31 | -------------------------------------------------------------------------------- /web_programming/daily_horoscope.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def horoscope(zodiac_sign: int, day: str) -> str: 6 | url = ( 7 | "https://www.horoscope.com/us/horoscopes/general/" 8 | f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}" 9 | ) 10 | soup = BeautifulSoup(requests.get(url).content, "html.parser") 11 | return soup.find("div", class_="main-horoscope").p.text 12 | 13 | 14 | if __name__ == "__main__": 15 | print("Daily Horoscope. \n") 16 | print( 17 | "enter your Zodiac sign number:\n", 18 | "1. Aries\n", 19 | "2. Taurus\n", 20 | "3. Gemini\n", 21 | "4. Cancer\n", 22 | "5. Leo\n", 23 | "6. Virgo\n", 24 | "7. Libra\n", 25 | "8. Scorpio\n", 26 | "9. Sagittarius\n", 27 | "10. Capricorn\n", 28 | "11. Aquarius\n", 29 | "12. Pisces\n", 30 | ) 31 | zodiac_sign = int(input("number> ").strip()) 32 | print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n") 33 | day = input("enter the day> ") 34 | horoscope_text = horoscope(zodiac_sign, day) 35 | print(horoscope_text) 36 | -------------------------------------------------------------------------------- /web_programming/fetch_bbc_news.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" 6 | 7 | 8 | def fetch_bbc_news(bbc_news_api_key: str) -> None: 9 | # fetching a list of articles in json format 10 | bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() 11 | # each article in the list is a dict 12 | for i, article in enumerate(bbc_news_page["articles"], 1): 13 | print(f"{i}.) {article['title']}") 14 | 15 | 16 | if __name__ == "__main__": 17 | fetch_bbc_news(bbc_news_api_key="") 18 | -------------------------------------------------------------------------------- /web_programming/fetch_jobs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scraping jobs given job title and location from indeed website 3 | """ 4 | from __future__ import annotations 5 | 6 | from typing import Generator 7 | 8 | import requests 9 | from bs4 import BeautifulSoup 10 | 11 | url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" 12 | 13 | 14 | def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]: 15 | soup = BeautifulSoup(requests.get(url + location).content, "html.parser") 16 | # This attribute finds out all the specifics listed in a job 17 | for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}): 18 | job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip() 19 | company_name = job.find("span", {"class": "company"}).text.strip() 20 | yield job_title, company_name 21 | 22 | 23 | if __name__ == "__main__": 24 | for i, job in enumerate(fetch_jobs("Bangalore"), 1): 25 | print(f"Job {i:>2} is {job[0]} at {job[1]}") 26 | -------------------------------------------------------------------------------- /web_programming/get_imdb_top_250_movies_csv.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import csv 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | 8 | 9 | def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: 10 | url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" 11 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 12 | titles = soup.find_all("td", attrs="titleColumn") 13 | ratings = soup.find_all("td", class_="ratingColumn imdbRating") 14 | return { 15 | title.a.text: float(rating.strong.text) 16 | for title, rating in zip(titles, ratings) 17 | } 18 | 19 | 20 | def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: 21 | movies = get_imdb_top_250_movies() 22 | with open(filename, "w", newline="") as out_file: 23 | writer = csv.writer(out_file) 24 | writer.writerow(["Movie title", "IMDb rating"]) 25 | for title, rating in movies.items(): 26 | writer.writerow([title, rating]) 27 | 28 | 29 | if __name__ == "__main__": 30 | write_movies() 31 | -------------------------------------------------------------------------------- /web_programming/get_imdbtop.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def imdb_top(imdb_top_n): 6 | base_url = ( 7 | f"https://www.imdb.com/search/title?title_type=" 8 | f"feature&sort=num_votes,desc&count={imdb_top_n}" 9 | ) 10 | source = BeautifulSoup(requests.get(base_url).content, "html.parser") 11 | for m in source.findAll("div", class_="lister-item mode-advanced"): 12 | print("\n" + m.h3.a.text) # movie's name 13 | print(m.find("span", attrs={"class": "genre"}).text) # genre 14 | print(m.strong.text) # movie's rating 15 | print(f"https://www.imdb.com{m.a.get('href')}") # movie's page link 16 | print("*" * 40) 17 | 18 | 19 | if __name__ == "__main__": 20 | imdb_top(input("How many movies would you like to see? ")) 21 | -------------------------------------------------------------------------------- /web_programming/instagram_pic.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | import requests 4 | from bs4 import BeautifulSoup 5 | 6 | if __name__ == "__main__": 7 | url = input("Enter image url: ").strip() 8 | print(f"Downloading image from {url} ...") 9 | soup = BeautifulSoup(requests.get(url).content, "html.parser") 10 | # The image URL is in the content field of the first meta tag with property og:image 11 | image_url = soup.find("meta", {"property": "og:image"})["content"] 12 | image_data = requests.get(image_url).content 13 | file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" 14 | with open(file_name, "wb") as fp: 15 | fp.write(image_data) 16 | print(f"Done. Image saved to disk as {file_name}.") 17 | -------------------------------------------------------------------------------- /web_programming/slack_message.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | 6 | def send_slack_message(message_body: str, slack_url: str) -> None: 7 | headers = {"Content-Type": "application/json"} 8 | response = requests.post(slack_url, json={"text": message_body}, headers=headers) 9 | if response.status_code != 200: 10 | raise ValueError( 11 | f"Request to slack returned an error {response.status_code}, " 12 | f"the response is:\n{response.text}" 13 | ) 14 | 15 | 16 | if __name__ == "__main__": 17 | # Set the slack url to the one provided by Slack when you create the webhook at 18 | # https://my.slack.com/services/new/incoming-webhook/ 19 | send_slack_message("", "") 20 | -------------------------------------------------------------------------------- /web_programming/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 | -------------------------------------------------------------------------------- /web_programming/world_covid19_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Provide the current worldwide COVID-19 statistics. 5 | This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. 6 | """ 7 | 8 | import requests 9 | from bs4 import BeautifulSoup 10 | 11 | 12 | def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: 13 | """ 14 | Return a dict of current worldwide COVID-19 statistics 15 | """ 16 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 17 | keys = soup.findAll("h1") 18 | values = soup.findAll("div", {"class": "maincounter-number"}) 19 | keys += soup.findAll("span", {"class": "panel-title"}) 20 | values += soup.findAll("div", {"class": "number-table-main"}) 21 | return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} 22 | 23 | 24 | if __name__ == "__main__": 25 | print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") 26 | for key, value in world_covid19_stats().items(): 27 | print(f"{key}\n{value}\n") 28 | --------------------------------------------------------------------------------