{"id":19590980,"url":"https://github.com/ahammadmejbah/python-problem-statement-and-solutions","last_synced_at":"2025-04-27T13:31:56.048Z","repository":{"id":198263229,"uuid":"700447139","full_name":"ahammadmejbah/Python-Problem-Statement-and-Solutions","owner":"ahammadmejbah","description":"Create a Python Problem Statement to challenge programmers. Specify a task, input/output requirements, and constraints. Ensure clarity and complexity to evaluate coding skills effectively.","archived":false,"fork":false,"pushed_at":"2023-11-04T14:20:41.000Z","size":111,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-08-28T20:40:53.951Z","etag":null,"topics":["data-science","machine","machine-learning","python","python3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ahammadmejbah.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-04T16:01:16.000Z","updated_at":"2024-01-13T21:09:51.000Z","dependencies_parsed_at":"2024-08-28T20:51:53.675Z","dependency_job_id":null,"html_url":"https://github.com/ahammadmejbah/Python-Problem-Statement-and-Solutions","commit_stats":null,"previous_names":["ahammadmejbah/python-problem-statement-and-solutions","bytesofintelligences/python-problem-statement-and-solutions"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahammadmejbah%2FPython-Problem-Statement-and-Solutions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahammadmejbah%2FPython-Problem-Statement-and-Solutions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahammadmejbah%2FPython-Problem-Statement-and-Solutions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahammadmejbah%2FPython-Problem-Statement-and-Solutions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ahammadmejbah","download_url":"https://codeload.github.com/ahammadmejbah/Python-Problem-Statement-and-Solutions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224072118,"owners_count":17251011,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-science","machine","machine-learning","python","python3"],"created_at":"2024-11-11T08:27:07.882Z","updated_at":"2024-11-11T08:27:09.317Z","avatar_url":"https://github.com/ahammadmejbah.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# **Dijkstras Algorithm**\n\nDijkstra's algorithm is a popular graph search algorithm used to find the shortest path from a source vertex to all other vertices in a weighted graph. It works by maintaining a set of vertices whose shortest distance from the source vertex is known and continually updates the distance values of the remaining vertices as it explores the graph.\n\nHere is a high-level overview of Dijkstra's algorithm:\n\n1. Create a list to store the shortest distance from the source vertex to each vertex in the graph. Initialize the distance of the source vertex to 0 and all other vertices to infinity.\n\n2. Create a set to keep track of visited vertices.\n\n3. While there are unvisited vertices:\n   a. Select the unvisited vertex with the smallest distance from the source vertex. This can be done using a priority queue or a min-heap data structure.\n   b. Mark the selected vertex as visited.\n   c. For each neighbor of the selected vertex that is unvisited:\n      - Calculate the distance from the source vertex to the neighbor through the selected vertex.\n      - If this distance is shorter than the current known distance to the neighbor, update the neighbor's distance value.\n   \n4. Repeat step 3 until all vertices have been visited.\n\nNow, let's implement Dijkstra's algorithm in Python:\n\n```python\nimport heapq\n\ndef dijkstra(graph, source):\n    # Initialize distances and visited set\n    distances = {vertex: float('infinity') for vertex in graph}\n    distances[source] = 0\n    visited = set()\n    \n    # Create a priority queue to store vertices and their distances\n    priority_queue = [(0, source)]\n    \n    while priority_queue:\n        # Get the vertex with the smallest distance from the priority queue\n        current_distance, current_vertex = heapq.heappop(priority_queue)\n        \n        # Skip if already visited\n        if current_vertex in visited:\n            continue\n        \n        # Mark the current vertex as visited\n        visited.add(current_vertex)\n        \n        # Update the distances to neighbors\n        for neighbor, weight in graph[current_vertex].items():\n            distance = current_distance + weight\n            if distance \u003c distances[neighbor]:\n                distances[neighbor] = distance\n                heapq.heappush(priority_queue, (distance, neighbor))\n    \n    return distances\n\n# Example usage:\ngraph = {\n    'A': {'B': 1, 'C': 4},\n    'B': {'A': 1, 'C': 2, 'D': 5},\n    'C': {'A': 4, 'B': 2, 'D': 1},\n    'D': {'B': 5, 'C': 1}\n}\n\nsource_vertex = 'A'\nshortest_distances = dijkstra(graph, source_vertex)\nprint(\"Shortest distances from\", source_vertex, \"to each vertex:\", shortest_distances)\n```\n\nIn this example, we have a weighted graph represented as a dictionary, where the keys are vertices, and the values are dictionaries of neighboring vertices and their edge weights. The `dijkstra` function returns the shortest distances from the source vertex 'A' to all other vertices in the graph.\n\n\n# **Markov Algorithm**\nA Markov algorithm, also known as a Markov procedure or Markov process, is a mathematical model used in computer science and mathematics for solving problems and manipulating strings or sequences of symbols. It's a type of algorithm that works by repeatedly applying a set of rules or transformations to a string until a specific condition is met. Markov algorithms are often used for tasks like string manipulation, pattern matching, and text processing.\n\nHere, I'll provide a basic overview of how a Markov algorithm works and some Python code to illustrate the concept.\n\n### Markov Algorithm Basics\n\nA Markov algorithm consists of a set of rules, each of which has two parts: a pattern to match in the input string and a replacement string. The algorithm starts with an initial input string and repeatedly applies these rules in a specific order until no more rules can be applied.\n\nThe algorithm continues until it reaches a halting state or until no further rules can be applied. It's important to ensure that the algorithm eventually halts, which can be achieved by having a rule that transforms the input into a state where no more rules apply.\n\n### Example Markov Algorithm in Python\n\nLet's consider a simple example of a Markov algorithm in Python that replaces \"A\" with \"B\" in a given string.\n\n```python\ndef markov_algorithm(input_string):\n    rules = [\n        (\"A\", \"B\"),\n    ]\n\n    while True:\n        applied = False  # Flag to track whether a rule was applied in this iteration\n\n        for pattern, replacement in rules:\n            if pattern in input_string:\n                input_string = input_string.replace(pattern, replacement)\n                applied = True\n\n        if not applied:\n            break  # No rules were applied, so we're done\n\n    return input_string\n\n# Test the Markov algorithm\ninitial_string = \"AAAAABAAA\"\nresult = markov_algorithm(initial_string)\nprint(\"Initial String:\", initial_string)\nprint(\"Final Result:\", result)\n```\n\nIn this example, we have one rule that replaces \"A\" with \"B\". The algorithm repeatedly checks the input string for occurrences of the pattern \"A\" and replaces them with \"B\" until no more \"A\" characters are present. When no rules can be applied in an iteration, the algorithm terminates.\n\n### Usage\n\nYou can customize the `rules` list to define more complex transformations or apply multiple rules in a specific order to achieve the desired output for your particular problem. Markov algorithms can be used for various text-processing tasks, and their flexibility makes them a useful tool for string manipulation.\n\n# Cumulative Standard Deviation\nCumulative standard deviation is a statistic that measures the dispersion or variability of a dataset as it accumulates over time or as new data points are added. It helps you understand how the spread of data changes as you incorporate more observations. To calculate the cumulative standard deviation, you'll need to keep track of the mean and variance as you add each new data point.\n\nHere's the formula for calculating the cumulative standard deviation:\n\n```\nCumulative Standard Deviation (σ_cumulative) = sqrt(Σ[(X_i - μ_cumulative)^2] / N)\n```\n\nWhere:\n- σ_cumulative is the cumulative standard deviation.\n- X_i is each individual data point.\n- μ_cumulative is the cumulative mean.\n- N is the number of data points.\n\nHere's a Python code snippet to calculate the cumulative standard deviation as you add new data points:\n\n```python\nimport math\n\ndef cumulative_std_dev(data):\n    cumulative_mean = 0  # Initialize the cumulative mean\n    cumulative_variance = 0  # Initialize the cumulative variance\n    cumulative_std_deviation = []  # List to store cumulative standard deviations\n\n    for i, x in enumerate(data, 1):\n        # Update the cumulative mean\n        cumulative_mean = (cumulative_mean * (i - 1) + x) / i\n\n        # Update the cumulative variance\n        cumulative_variance = (cumulative_variance * (i - 1) + (x - cumulative_mean) ** 2) / i\n\n        # Calculate the cumulative standard deviation\n        cumulative_std_dev = math.sqrt(cumulative_variance)\n\n        cumulative_std_deviation.append(cumulative_std_dev)\n\n    return cumulative_std_deviation\n\n# Example usage:\ndata = [1, 2, 3, 4, 5]\ncumulative_std = cumulative_std_dev(data)\nprint(cumulative_std)\n```\n\nIn this code:\n\n- `cumulative_mean` keeps track of the cumulative mean as new data points are added.\n- `cumulative_variance` keeps track of the cumulative variance as new data points are added.\n- `cumulative_std_deviation` is a list that stores the cumulative standard deviations after each data point is added to the sequence.\n\nThe function `cumulative_std_dev` takes a list of data points as input and returns a list of cumulative standard deviations. You can add new data points to the `data` list, and the function will update the cumulative standard deviation accordingly.\n\n\n# **Parallel Brute Force**\nParallel brute force is a technique used in computer science and cryptography to speed up the process of trying all possible combinations or solutions to a problem by running multiple threads or processes simultaneously. This can significantly reduce the time it takes to find a solution, especially for problems with a large search space. In this article, we'll explore how to implement parallel brute force in Python using the multiprocessing module.\n\nLet's say you have a problem where you need to find a specific combination of characters or numbers, and you want to try all possible combinations until you find the correct one. This can be a time-consuming process, but by parallelizing the task, you can utilize multiple CPU cores to speed it up.\n\n\n``` python\n\nimport itertools\nimport multiprocessing\n\ndef brute_force(charset, length):\n    for attempt in itertools.product(charset, repeat=length):\n        yield ''.join(attempt)\n\ndef check_password(password, guess):\n    return password == guess\n\ndef parallel_brute_force(password, charset, length, num_processes):\n    manager = multiprocessing.Manager()\n    result_queue = manager.Queue()\n\n    def worker(password, charset, length, result_queue):\n        for guess in brute_force(charset, length):\n            if check_password(password, guess):\n                result_queue.put(guess)\n                break\n\n    processes = []\n    for _ in range(num_processes):\n        process = multiprocessing.Process(target=worker, args=(password, charset, length, result_queue))\n        process.start()\n        processes.append(process)\n\n    for process in processes:\n        process.join()\n\n    if not result_queue.empty():\n        return result_queue.get()\n    else:\n        return None\n\nif __name__ == '__main__':\n    password = 'password123'\n    charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n    length = len(password)\n    num_processes = multiprocessing.cpu_count()\n\n    cracked_password = parallel_brute_force(password, charset, length, num_processes)\n    if cracked_password:\n        print(f'Password cracked: {cracked_password}')\n    else:\n        print('Password not cracked')\n\n```\n\n# **Object Serialization** \nObject serialization is a technique used in programming to convert an object's state into a byte stream. This byte stream can then be stored in a file or sent over a network. The process of converting the byte stream back into an object is called deserialization.\n\nObject serialization is particularly useful in distributed systems, where objects need to be sent between different processes or machines. It can also be used in applications that require persisting an object's state across different program runs.\n\nHere's an example of how to use object serialization in Python:\n\n\n``` python\nimport pickle\n​\nclass Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n​\n    def __str__(self):\n        return f'{self.name}, {self.age} years old'\n​\n# Create a Person object\nperson = Person('Alice', 30)\n​\n# Serialize the Person object into a byte stream\nwith open('person.pkl', 'wb') as f:\n    pickle.dump(person, f)\n​\n# Deserialize the byte stream back into a Person object\nwith open('person.pkl', 'rb') as f:\n    loaded_person = pickle.load(f)\n​\nprint(loaded_person) # Output: Alice, 30 years old\n​\n```\n\nIn this example, we define a `Person` class with a name and age. We then create a `Person` object and serialize it into a byte stream using the `pickle.dump` function. The byte stream is stored in a file named 'person.pkl'.\n\nLater, we deserialize the byte stream back into a `Person` object using the `pickle.load` function. Finally, we print the deserialized `Person` object, which should have the same name and age as the original object.\n\nIt's important to note that object serialization can be a complex topic, especially when dealing with complex object graphs or cyclic references. However, the example provided here should give you a basic understanding of how object serialization works in Python.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahammadmejbah%2Fpython-problem-statement-and-solutions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahammadmejbah%2Fpython-problem-statement-and-solutions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahammadmejbah%2Fpython-problem-statement-and-solutions/lists"}