internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: TheAlgorithms/Python

Issue:
Add largest power of 2 less than or equal to a given number
### Feature description

This can be done by left-shifting the given number and stopping when you reach the first set bit. And then you can find the largest power of two by finding the difference between the length of the given number when converting it to binary form and the no of times you had to shift to find the first set bit. 


Discussion:
Hello Sir,
I want to work on this. Can you please assign me this issue.

Resolving patch:
diff --git a/bit_manipulation/largest_pow_of_two_le_num.py b/bit_manipulation/largest_pow_of_two_le_num.py
new file mode 100644
--- /dev/null
+++ b/bit_manipulation/largest_pow_of_two_le_num.py
@@ -0,0 +1,60 @@
+"""
+Author  : Naman Sharma
+Date    : October 2, 2023
+
+Task:
+To Find the largest power of 2 less than or equal to a given number.
+
+Implementation notes: Use bit manipulation.
+We start from 1 & left shift the set bit to check if (res<<1)<=number.
+Each left bit shift represents a pow of 2.
+
+For example:
+number: 15
+res:    1   0b1
+        2   0b10
+        4   0b100
+        8   0b1000
+        16  0b10000 (Exit)
+"""
+
+
+def largest_pow_of_two_le_num(number: int) -> int:
+    """
+    Return the largest power of two less than or equal to a number.
+
+    >>> largest_pow_of_two_le_num(0)
+    0
+    >>> largest_pow_of_two_le_num(1)
+    1
+    >>> largest_pow_of_two_le_num(-1)
+    0
+    >>> largest_pow_of_two_le_num(3)
+    2
+    >>> largest_pow_of_two_le_num(15)
+    8
+    >>> largest_pow_of_two_le_num(99)
+    64
+    >>> largest_pow_of_two_le_num(178)
+    128
+    >>> largest_pow_of_two_le_num(999999)
+    524288
+    >>> largest_pow_of_two_le_num(99.9)
+    Traceback (most recent call last):
+        ...
+    TypeError: Input value must be a 'int' type
+    """
+    if isinstance(number, float):
+        raise TypeError("Input value must be a 'int' type")
+    if number <= 0:
+        return 0
+    res = 1
+    while (res << 1) <= number:
+        res <<= 1
+    return res
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
Concatenate/consolidate all algorithms with different implementations
### Feature description

There are lots of algorithms with the same concept but different implementations/methods in different files. All these should be moved into one file


Discussion:
hello sir
Can I take this issue.

@CaedenPH Please assign this task to me.
@digital-dev-07 Read the [contributing guidelines](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md#contribution).
> If you are interested in resolving an [open issue](https://github.com/TheAlgorithms/Python/issues), simply make a pull request with your proposed fix. We do not assign issues in this repo so please do not ask for permission to work on an issue.

Resolving patch:
diff --git a/backtracking/minmax.py b/backtracking/minmax.py
deleted file mode 100644
--- a/backtracking/minmax.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""
-Minimax helps to achieve maximum score in a game by checking all possible moves.
-
-"""
-from __future__ import annotations
-
-import math
-
-
-def minimax(
-    depth: int, node_index: int, is_max: bool, scores: list[int], height: float
-) -> int:
-    """
-    depth is current depth in game tree.
-    node_index is index of current node in scores[].
-    scores[] contains the leaves of game tree.
-    height is maximum height of game tree.
-
-    >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]
-    >>> height = math.log(len(scores), 2)
-    >>> minimax(0, 0, True, scores, height)
-    65
-    >>> minimax(-1, 0, True, scores, height)
-    Traceback (most recent call last):
-        ...
-    ValueError: Depth cannot be less than 0
-    >>> minimax(0, 0, True, [], 2)
-    Traceback (most recent call last):
-        ...
-    ValueError: Scores cannot be empty
-    >>> scores = [3, 5, 2, 9, 12, 5, 23, 23]
-    >>> height = math.log(len(scores), 2)
-    >>> minimax(0, 0, True, scores, height)
-    12
-    """
-
-    if depth < 0:
-        raise ValueError("Depth cannot be less than 0")
-
-    if not scores:
-        raise ValueError("Scores cannot be empty")
-
-    if depth == height:
-        return scores[node_index]
-
-    return (
-        max(
-            minimax(depth + 1, node_index * 2, False, scores, height),
-            minimax(depth + 1, node_index * 2 + 1, False, scores, height),
-        )
-        if is_max
-        else min(
-            minimax(depth + 1, node_index * 2, True, scores, height),
-            minimax(depth + 1, node_index * 2 + 1, True, scores, height),
-        )
-    )
-
-
-def main() -> None:
-    scores = [90, 23, 6, 33, 21, 65, 123, 34423]
-    height = math.log(len(scores), 2)
-    print(f"Optimal value : {minimax(0, 0, True, scores, height)}")
-
-
-if __name__ == "__main__":
-    import doctest
-
-    doctest.testmod()
-    main()


Test patch:
Repository: TheAlgorithms/Python

Issue:
Add camelCase to snake_case conversion algorithm
### Feature description

In the 'strings' folder there is an algorithm that converts snake_case to camelCase. 
But what's missing is camel to snake algorithm that handles numbers. It should be added.


Discussion:

Resolving patch:
diff --git a/strings/camel_case_to_snake_case.py b/strings/camel_case_to_snake_case.py
new file mode 100644
--- /dev/null
+++ b/strings/camel_case_to_snake_case.py
@@ -0,0 +1,60 @@
+def camel_to_snake_case(input_str: str) -> str:
+    """
+    Transforms a camelCase (or PascalCase) string to snake_case
+
+    >>> camel_to_snake_case("someRandomString")
+    'some_random_string'
+
+    >>> camel_to_snake_case("SomeRandomStr#ng")
+    'some_random_str_ng'
+
+    >>> camel_to_snake_case("123someRandom123String123")
+    '123_some_random_123_string_123'
+
+    >>> camel_to_snake_case("123SomeRandom123String123")
+    '123_some_random_123_string_123'
+
+    >>> camel_to_snake_case(123)
+    Traceback (most recent call last):
+        ...
+    ValueError: Expected string as input, found <class 'int'>
+
+    """
+
+    # check for invalid input type
+    if not isinstance(input_str, str):
+        msg = f"Expected string as input, found {type(input_str)}"
+        raise ValueError(msg)
+
+    snake_str = ""
+
+    for index, char in enumerate(input_str):
+        if char.isupper():
+            snake_str += "_" + char.lower()
+
+        # if char is lowercase but proceeded by a digit:
+        elif input_str[index - 1].isdigit() and char.islower():
+            snake_str += "_" + char
+
+        # if char is a digit proceeded by a letter:
+        elif input_str[index - 1].isalpha() and char.isnumeric():
+            snake_str += "_" + char.lower()
+
+        # if char is not alphanumeric:
+        elif not char.isalnum():
+            snake_str += "_"
+
+        else:
+            snake_str += char
+
+    # remove leading underscore
+    if snake_str[0] == "_":
+        snake_str = snake_str[1:]
+
+    return snake_str
+
+
+if __name__ == "__main__":
+    from doctest import testmod
+
+    testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
Convert to Base -2
### Feature description

Found a solution to this problem.

I would like to solve this issue.


Discussion:
Hi, I want to contribute to this issue. However I couldn't find the code file in the repo. Can you help me out on where to begin? (I'm a beginner to open source and would really appreciate some help)
Hey, I am a beginner as well. Just contributed to one project before, but
never contributed to such a big project. I am still figuring out how to
contribute to such big repo.

I would be very happy to collab with u, regarding this.

On Tue, 3 Oct 2023, 19:45 RamDanny, ***@***.***> wrote:

> Hi, I want to contribute to this issue. However I couldn't find the code
> file in the repo. Can you help me out on where to begin? (I'm a beginner
> and would really appreciate some help)
>
> —
> Reply to this email directly, view it on GitHub
> <https://github.com/TheAlgorithms/Python/issues/9588#issuecomment-1745071161>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AZLHEKYMIVWHUI66WQYABJDX5QMY3AVCNFSM6AAAAAA5Q6H5SKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTONBVGA3TCMJWGE>
> .
> You are receiving this because you authored the thread.Message ID:
> ***@***.***>
>


Resolving patch:
diff --git a/maths/base_neg2_conversion.py b/maths/base_neg2_conversion.py
new file mode 100644
--- /dev/null
+++ b/maths/base_neg2_conversion.py
@@ -0,0 +1,37 @@
+def decimal_to_negative_base_2(num: int) -> int:
+    """
+    This function returns the number negative base 2
+        of the decimal number of the input data.
+
+    Args:
+        int: The decimal number to convert.
+
+    Returns:
+        int: The negative base 2 number.
+
+    Examples:
+        >>> decimal_to_negative_base_2(0)
+        0
+        >>> decimal_to_negative_base_2(-19)
+        111101
+        >>> decimal_to_negative_base_2(4)
+        100
+        >>> decimal_to_negative_base_2(7)
+        11011
+    """
+    if num == 0:
+        return 0
+    ans = ""
+    while num != 0:
+        num, rem = divmod(num, -2)
+        if rem < 0:
+            rem += 2
+            num += 1
+        ans = str(rem) + ans
+    return int(ans)
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
sigmoid, tanh and relu should be moved to neural_network/activation_functions from maths/
### Feature description

`sigmoid.py`, `tanh.py`, `sigmoid_linear_unit.py` and `relu.py` should be moved to neural_network/activation_functions.


Discussion:
@AdarshAcharya5 , why you want to move those .py files?
is this still a requirement and open for contribution?

Hey
I have been working with neural net for quite a while now (check my GitHub). would love to work on this issue.
Am new to open source and would love any help whatsoever.
can you assign me this task please.
@rohan472000 Functions such as sigmoid, tanh, and ReLU are nowadays commonly used as activation functions for neural networks. Sigmoid (or more specifically the logistic function) and tanh are still well-known mathematical functions outside of ML, so I think those should stay in the `maths/` directory. However, ReLU is pretty much only known as an activation function as far as I know, so I think it's appropriate to move that algorithm to `neural_network/activation_functions`.

Resolving patch:
diff --git a/maths/relu.py b/neural_network/activation_functions/rectified_linear_unit.py
similarity index 100%
rename from maths/relu.py
rename to neural_network/activation_functions/rectified_linear_unit.py


Test patch:
Repository: TheAlgorithms/Python

Issue:
Find Equilibrium index in an array
### Feature description

The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. 


Discussion:

Resolving patch:
diff --git a/data_structures/arrays/equilibrium_index_in_array.py b/data_structures/arrays/equilibrium_index_in_array.py
new file mode 100644
--- /dev/null
+++ b/data_structures/arrays/equilibrium_index_in_array.py
@@ -0,0 +1,59 @@
+"""
+Find the Equilibrium Index of an Array.
+Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
+
+Python doctests can be run with the following command:
+python -m doctest -v equilibrium_index.py
+
+Given a sequence arr[] of size n, this function returns
+an equilibrium index (if any) or -1 if no equilibrium index exists.
+
+The equilibrium index of an array is an index such that the sum of
+elements at lower indexes is equal to the sum of elements at higher indexes.
+
+
+
+Example Input:
+arr = [-7, 1, 5, 2, -4, 3, 0]
+Output: 3
+
+"""
+
+
+def equilibrium_index(arr: list[int], size: int) -> int:
+    """
+    Find the equilibrium index of an array.
+
+    Args:
+        arr : The input array of integers.
+        size : The size of the array.
+
+    Returns:
+        int: The equilibrium index or -1 if no equilibrium index exists.
+
+    Examples:
+        >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0], 7)
+        3
+        >>> equilibrium_index([1, 2, 3, 4, 5], 5)
+        -1
+        >>> equilibrium_index([1, 1, 1, 1, 1], 5)
+        2
+        >>> equilibrium_index([2, 4, 6, 8, 10, 3], 6)
+        -1
+    """
+    total_sum = sum(arr)
+    left_sum = 0
+
+    for i in range(size):
+        total_sum -= arr[i]
+        if left_sum == total_sum:
+            return i
+        left_sum += arr[i]
+
+    return -1
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
Match a pattern and String using backtracking
### What would you like to share?

Given a string, find out if string follows a given pattern or not without using any regular expressions. We can solve this problem with the help of Backtracking. 

### Additional information

_No response_


Discussion:

Resolving patch:
diff --git a/backtracking/match_word_pattern.py b/backtracking/match_word_pattern.py
new file mode 100644
--- /dev/null
+++ b/backtracking/match_word_pattern.py
@@ -0,0 +1,61 @@
+def match_word_pattern(pattern: str, input_string: str) -> bool:
+    """
+    Determine if a given pattern matches a string using backtracking.
+
+    pattern: The pattern to match.
+    input_string: The string to match against the pattern.
+    return: True if the pattern matches the string, False otherwise.
+
+    >>> match_word_pattern("aba", "GraphTreesGraph")
+    True
+
+    >>> match_word_pattern("xyx", "PythonRubyPython")
+    True
+
+    >>> match_word_pattern("GG", "PythonJavaPython")
+    False
+    """
+
+    def backtrack(pattern_index: int, str_index: int) -> bool:
+        """
+        >>> backtrack(0, 0)
+        True
+
+        >>> backtrack(0, 1)
+        True
+
+        >>> backtrack(0, 4)
+        False
+        """
+        if pattern_index == len(pattern) and str_index == len(input_string):
+            return True
+        if pattern_index == len(pattern) or str_index == len(input_string):
+            return False
+        char = pattern[pattern_index]
+        if char in pattern_map:
+            mapped_str = pattern_map[char]
+            if input_string.startswith(mapped_str, str_index):
+                return backtrack(pattern_index + 1, str_index + len(mapped_str))
+            else:
+                return False
+        for end in range(str_index + 1, len(input_string) + 1):
+            substr = input_string[str_index:end]
+            if substr in str_map:
+                continue
+            pattern_map[char] = substr
+            str_map[substr] = char
+            if backtrack(pattern_index + 1, end):
+                return True
+            del pattern_map[char]
+            del str_map[substr]
+        return False
+
+    pattern_map: dict[str, str] = {}
+    str_map: dict[str, str] = {}
+    return backtrack(0, 0)
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
[Add] : trapped water program by using DYNAMIC PROGRAMMING
### Feature description

Trapped Water problem - using Dynamic Programming : 

![Screenshot 2023-10-07 at 21-10-47 Trapping Rainwater - https __www apnacollege in_path-player courseid alpha-batch-4 unit 64454bee464c180a3c0b664711Unit](https://github.com/TheAlgorithms/Python/assets/118645569/0cbe034f-66fb-4e0e-9742-6857ed5efa26)


![Screenshot 2023-10-07 at 21-19-24 Trapping rain water in javascript - LearnersBucket](https://github.com/TheAlgorithms/Python/assets/118645569/0eeac04d-b958-4919-9889-d470ec7e727a)



Discussion:

Resolving patch:
diff --git a/dynamic_programming/trapped_water.py b/dynamic_programming/trapped_water.py
new file mode 100644
--- /dev/null
+++ b/dynamic_programming/trapped_water.py
@@ -0,0 +1,60 @@
+"""
+Given an array of non-negative integers representing an elevation map where the width
+of each bar is 1, this program calculates how much rainwater can be trapped.
+
+Example - height = (0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)
+Output: 6
+This problem can be solved using the concept of "DYNAMIC PROGRAMMING".
+
+We calculate the maximum height of bars on the left and right of every bar in array.
+Then iterate over the width of structure and at each index.
+The amount of water that will be stored is equal to minimum of maximum height of bars
+on both sides minus height of bar at current position.
+"""
+
+
+def trapped_rainwater(heights: tuple[int, ...]) -> int:
+    """
+    The trapped_rainwater function calculates the total amount of rainwater that can be
+    trapped given an array of bar heights.
+    It uses a dynamic programming approach, determining the maximum height of bars on
+    both sides for each bar, and then computing the trapped water above each bar.
+    The function returns the total trapped water.
+
+    >>> trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1))
+    6
+    >>> trapped_rainwater((7, 1, 5, 3, 6, 4))
+    9
+    >>> trapped_rainwater((7, 1, 5, 3, 6, -1))
+    Traceback (most recent call last):
+        ...
+    ValueError: No height can be negative
+    """
+    if not heights:
+        return 0
+    if any(h < 0 for h in heights):
+        raise ValueError("No height can be negative")
+    length = len(heights)
+
+    left_max = [0] * length
+    left_max[0] = heights[0]
+    for i, height in enumerate(heights[1:], start=1):
+        left_max[i] = max(height, left_max[i - 1])
+
+    right_max = [0] * length
+    right_max[-1] = heights[-1]
+    for i in range(length - 2, -1, -1):
+        right_max[i] = max(heights[i], right_max[i + 1])
+
+    return sum(
+        min(left, right) - height
+        for left, right, height in zip(left_max, right_max, heights)
+    )
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()
+    print(f"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }")
+    print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")


Test patch:
Repository: TheAlgorithms/Python

Issue:
blockchain section doesn't contain blockchain-related algorithms
### What would you like to share?

The blockchain section contains a README which starts talking about blockchains, DLTs and cryptography, as expected, but then includes links to the Chinese Remainder Theorem and modular division.  

While certainly interesting topics, they are not strictly related to blockchains. 

The Chinese Remainder Theorem is used in many RSA implementations, but RSA is not used in blockchains like Bitcoin and Ethereum.

 Hashes such as SHA256 are by far more related to blockchains, but they are implemented in the hash/ directory.

I believe the blockchain section, in its current version, is confusing.

Some possible solutions:
- amend the documentation
- move CRTs, modular division to a new directory (maybe number theory? Linear algebra already exists and looks like a nice precedent)
- rename the blockchain directory


### Additional information

_No response_


Discussion:
I completely agree. I personally don't think that any of the algorithms in the blockchain directory are _directly_ related to blockchains, and they'd belong better under another directory such as maths. I'd be in favor of removing the blockchain directory entirely and relocating the algorithms. @cclauss, thoughts?
# amend the documentation

I would really like to continue having a blockchain directory but I am OK if we remove non-blockchain algorithms and text.  Let's have a place that helps visitors learn about blockchain.

Resolving patch:
diff --git a/blockchain/chinese_remainder_theorem.py b/maths/chinese_remainder_theorem.py
similarity index 100%
rename from blockchain/chinese_remainder_theorem.py
rename to maths/chinese_remainder_theorem.py
diff --git a/blockchain/modular_division.py b/maths/modular_division.py
similarity index 100%
rename from blockchain/modular_division.py
rename to maths/modular_division.py


Test patch:
Repository: TheAlgorithms/Python

Issue:
[Add] : Best time to buy and sell stock program by using GREEDY 
### Feature description

Best time to buy and sell stock program - Under GREEDY METHODS

![image](https://github.com/TheAlgorithms/Python/assets/118645569/b7ee224a-34f0-49c7-ad32-68499945182f)


![image](https://github.com/TheAlgorithms/Python/assets/118645569/9f891151-4880-42ec-9072-ccaf2a038e3c)


![image](https://github.com/TheAlgorithms/Python/assets/118645569/20a8a176-754d-4594-ae49-7dba7ad77bfc)



Discussion:

Resolving patch:
diff --git a/greedy_methods/best_time_to_buy_and_sell_stock.py b/greedy_methods/best_time_to_buy_and_sell_stock.py
new file mode 100644
--- /dev/null
+++ b/greedy_methods/best_time_to_buy_and_sell_stock.py
@@ -0,0 +1,42 @@
+"""
+Given a list of stock prices calculate the maximum profit that can be made from a
+single buy and sell of one share of stock.  We only allowed to complete one buy
+transaction and one sell transaction but must buy before we sell.
+
+Example : prices = [7, 1, 5, 3, 6, 4]
+max_profit will return 5 - which is by buying at price 1 and selling at price 6.
+
+This problem can be solved using the concept of "GREEDY ALGORITHM".
+
+We iterate over the price array once, keeping track of the lowest price point
+(buy) and the maximum profit we can get at each point.  The greedy choice at each point
+is to either buy at the current price if it's less than our current buying price, or
+sell at the current price if the profit is more than our current maximum profit.
+"""
+
+
+def max_profit(prices: list[int]) -> int:
+    """
+    >>> max_profit([7, 1, 5, 3, 6, 4])
+    5
+    >>> max_profit([7, 6, 4, 3, 1])
+    0
+    """
+    if not prices:
+        return 0
+
+    min_price = prices[0]
+    max_profit: int = 0
+
+    for price in prices:
+        min_price = min(price, min_price)
+        max_profit = max(price - min_price, max_profit)
+
+    return max_profit
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()
+    print(max_profit([7, 1, 5, 3, 6, 4]))


Test patch:
Repository: TheAlgorithms/Python

Issue:
missing_number algorithm dosen't work as intended (bit_manipulation/missing_number.py)
### Repository commit

d0c54acd75cedf14cff353869482a0487fea1697

### Python version (python --version)

Python 3.12.0

### Dependencies version (pip freeze)

setuptools==68.2.2
wheel==0.41.2

### Expected behavior

for array [1,3,4,5,6] the output should be 2

### Actual behavior

the output got is 4


Discussion:

Resolving patch:
diff --git a/bit_manipulation/missing_number.py b/bit_manipulation/missing_number.py
--- a/bit_manipulation/missing_number.py
+++ b/bit_manipulation/missing_number.py
@@ -11,11 +11,18 @@ def find_missing_number(nums: list[int]) -> int:
     Example:
         >>> find_missing_number([0, 1, 3, 4])
         2
+        >>> find_missing_number([1, 3, 4, 5, 6])
+        2
+        >>> find_missing_number([6, 5, 4, 2, 1])
+        3
+        >>> find_missing_number([6, 1, 5, 3, 4])
+        2
     """
-    n = len(nums)
-    missing_number = n
+    low = min(nums)
+    high = max(nums)
+    missing_number = high
 
-    for i in range(n):
-        missing_number ^= i ^ nums[i]
+    for i in range(low, high):
+        missing_number ^= i ^ nums[i - low]
 
     return missing_number


Test patch:
Repository: TheAlgorithms/Python

Issue:
Adding Gaussian Error Linear Unit to neural network activation functions
### What would you like to share?

I would like to contribute the Gaussian Error Linear Unit (GELU) activation function file in this repository under the neural network activation functions folder.

### Additional information

_No response_


Discussion:

Resolving patch:
diff --git a/maths/gaussian_error_linear_unit.py b/neural_network/activation_functions/gaussian_error_linear_unit.py
similarity index 100%
rename from maths/gaussian_error_linear_unit.py
rename to neural_network/activation_functions/gaussian_error_linear_unit.py


Test patch: