ronantakizawa/codereview-bench huggingface dataset:
Repository: Textualize/rich
File: tests/test_cells.py (Python)

Code before:
        assert (
            cells.cell_len(
                cells.set_cell_size(
                    "เป็นเกมที่ต้องมีความอดทนมากที่สุดตั้งเเต่เคยเล่นมา", size
                )
            )
            == size
        )


def test_chop_cells():
    """Simple example of splitting cells into lines of width 3."""
    text = "abcdefghijk"
    assert chop_cells(text, 3) == ["abc", "def", "ghi", "jk"]


def test_chop_cells_double_width_boundary():
    """The available width lies within a double-width character."""
    text = "ありがとう"
    assert chop_cells(text, 3) == ["あ", "り", "が", "と", "う"]


def test_chop_cells_mixed_width():
    """Mixed single and double-width characters."""
    text = "あ1り2が3と4う56"
    assert chop_cells(text, 3) == ["あ1", "り2", "が3", "と4", "う5", "6"]


Review comment (suggestion):
I mixed it up a bit more to be less regular.
(I did this by hand and didn't run the test after! I also just copied and pasted some characters, maybe there was some meaning in here that I butchered... 😬)

```suggestion
    text = "あ1り2がり34とりう56"
    assert chop_cells(text, 3) == ["あ1", "り2", "が", "り3", "4と", "り", "う5", "6"]
```

Code after:
        assert (
            cells.cell_len(
                cells.set_cell_size(
                    "เป็นเกมที่ต้องมีความอดทนมากที่สุดตั้งเเต่เคยเล่นมา", size
                )
            )
            == size
        )


def test_chop_cells():
    """Simple example of splitting cells into lines of width 3."""
    text = "abcdefghijk"
    assert chop_cells(text, 3) == ["abc", "def", "ghi", "jk"]


def test_chop_cells_double_width_boundary():
    """The available width lies within a double-width character."""
    text = "ありがとう"
    assert chop_cells(text, 3) == ["あ", "り", "が", "と", "う"]


def test_chop_cells_mixed_width():
    """Mixed single and double-width characters."""
    text = "あ1り234が5と6う78"
    assert chop_cells(text, 3) == ["あ1", "り2", "34", "が5", "と6", "う7", "8"]
Repository: TheAlgorithms/Python
File: sorts/cyclic_sort.py (Python)

Code before:
"""
This is a pure Python implementation of the Cyclic Sort algorithm.

For doctests run following command:
python -m doctest -v cyclic_sort.py
or
python3 -m doctest -v cyclic_sort.py
For manual testing run:
python cyclic_sort.py
"""


def cyclic_sort(nums: list) -> list:
    """
    Sorts the input list in-place using the Cyclic Sort algorithm.

    :param nums: List of integers to be sorted.
    :return: The same list sorted in ascending order.

    Time complexity: O(n), where n is the number of elements in the list.

    Examples:
    >>> cyclic_sort([3, 5, 2, 1, 4])
    [1, 2, 3, 4, 5]
    >>> cyclic_sort([])
    []
    """

    # Perform cyclic sort
    i = 0
    while i < len(nums):
        # Calculate the correct index for the current element
        correct_index = nums[i] - 1
        # If the current element is not at its correct position,
        # swap it with the element at its correct index
        if nums[i] != nums[correct_index]:
            nums[i], nums[correct_index] = nums[correct_index], nums[i]
        else:
            # If the current element is already in its correct position,
            # move to the next element

Review comment (bug):
I'd recommend adding the input constraints.

This algorithm only works correctly when the elements range from `1` to `n` with no duplicates. Stating this constraint on the inputs to any potential users of the algorithm can help prevent confusion should they provide a list of integers that does not fit the criteria and end up in an infinite loop or some other unexpected behaviour.

Code after:
"""
This is a pure Python implementation of the Cyclic Sort algorithm.

For doctests run following command:
python -m doctest -v cyclic_sort.py
or
python3 -m doctest -v cyclic_sort.py
For manual testing run:
python cyclic_sort.py
or
python3 cyclic_sort.py
"""


def cyclic_sort(nums: list[int]) -> list[int]:
    """
    Sorts the input list of n integers from 1 to n in-place
    using the Cyclic Sort algorithm.

    :param nums: List of n integers from 1 to n to be sorted.
    :return: The same list sorted in ascending order.

    Time complexity: O(n), where n is the number of integers in the list.

    Examples:
    >>> cyclic_sort([])
    []
    >>> cyclic_sort([3, 5, 2, 1, 4])
    [1, 2, 3, 4, 5]
    """

    # Perform cyclic sort
    index = 0
    while index < len(nums):
        # Calculate the correct index for the current element
        correct_index = nums[index] - 1
        # If the current element is not at its correct position,
        # swap it with the element at its correct index
        if index != correct_index:
            nums[index], nums[correct_index] = nums[correct_index], nums[index]
Repository: TheAlgorithms/Python
File: sorts/cyclic_sort.py (Python)

Code before:
"""
This is a pure Python implementation of the Cyclic Sort algorithm.

For doctests run following command:
python -m doctest -v cyclic_sort.py
or
python3 -m doctest -v cyclic_sort.py
For manual testing run:
python cyclic_sort.py
"""


def cyclic_sort(nums: list) -> list:
    """
    Sorts the input list in-place using the Cyclic Sort algorithm.

    :param nums: List of integers to be sorted.
    :return: The same list sorted in ascending order.

    Time complexity: O(n), where n is the number of elements in the list.

    Examples:
    >>> cyclic_sort([3, 5, 2, 1, 4])
    [1, 2, 3, 4, 5]
    >>> cyclic_sort([])
    []
    """

    # Perform cyclic sort
    i = 0
    while i < len(nums):
        # Calculate the correct index for the current element
        correct_index = nums[i] - 1
        # If the current element is not at its correct position,
        # swap it with the element at its correct index
        if nums[i] != nums[correct_index]:
            nums[i], nums[correct_index] = nums[correct_index], nums[i]
        else:
            # If the current element is already in its correct position,
            # move to the next element
            i += 1

    return nums


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    user_input = input("Enter numbers separated by a comma:\n").strip()

Review comment (refactor):
Similar to above, I'd recommend adding an example to demonstrate what happens if the list contains elements outside the expected range (a non-positive integer) or duplicates are present in the list. This would show why this algorithm should not be used for those sets of values.

Code after:
"""
This is a pure Python implementation of the Cyclic Sort algorithm.

For doctests run following command:
python -m doctest -v cyclic_sort.py
or
python3 -m doctest -v cyclic_sort.py
For manual testing run:
python cyclic_sort.py
or
python3 cyclic_sort.py
"""


def cyclic_sort(nums: list[int]) -> list[int]:
    """
    Sorts the input list of n integers from 1 to n in-place
    using the Cyclic Sort algorithm.

    :param nums: List of n integers from 1 to n to be sorted.
    :return: The same list sorted in ascending order.

    Time complexity: O(n), where n is the number of integers in the list.

    Examples:
    >>> cyclic_sort([])
    []
    >>> cyclic_sort([3, 5, 2, 1, 4])
    [1, 2, 3, 4, 5]
    """

    # Perform cyclic sort
    index = 0
    while index < len(nums):
        # Calculate the correct index for the current element
        correct_index = nums[index] - 1
        # If the current element is not at its correct position,
        # swap it with the element at its correct index
        if index != correct_index:
            nums[index], nums[correct_index] = nums[correct_index], nums[index]
        else:
            # If the current element is already in its correct position,
            # move to the next element
            index += 1

    return nums


if __name__ == "__main__":
    import doctest
Repository: TheAlgorithms/Python
File: physics/period_of_pendulum.py (Python)

Code before:

Reference : https://byjus.com/jee/simple-pendulum/
"""
from math import pi

from scipy.constants import g


def period_of_pendulum(length: float) -> float:
    """
    >>> period_of_pendulum(1.23)
    2.2252155506257845
    >>> period_of_pendulum(2.37)
    3.0888278441908574
    >>> period_of_pendulum(5.63)
    4.76073193364765
    >>> period_of_pendulum(-12)
    Traceback (most recent call last):
        ...
    ValueError: The length should be non-negative
    >>> period_of_pendulum(0)
    0.0
    """
    if length < 0:
        raise ValueError("The length should be non-negative")
    return (2 * pi) * (length / g) ** 0.5


if __name__ == "__main__":
    import doctest

    doctest.testmod()


Review comment (suggestion):
```suggestion
    return 2 * pi * (length / g) ** 0.5
```
Minor nitpick: the parentheses around the `2 * pi` are unnecessary

Code after:

Reference : https://byjus.com/jee/simple-pendulum/
"""

from math import pi

from scipy.constants import g


def period_of_pendulum(length: float) -> float:
    """
    >>> period_of_pendulum(1.23)
    2.2252155506257845
    >>> period_of_pendulum(2.37)
    3.0888278441908574
    >>> period_of_pendulum(5.63)
    4.76073193364765
    >>> period_of_pendulum(-12)
    Traceback (most recent call last):
        ...
    ValueError: The length should be non-negative
    >>> period_of_pendulum(0)
    0.0
    """
    if length < 0:
        raise ValueError("The length should be non-negative")
    return 2 * pi * (length / g) ** 0.5


if __name__ == "__main__":
    import doctest

    doctest.testmod()
Repository: TheAlgorithms/Python
File: maths/geometric_mean.py (Python)

Code before:
    Traceback (most recent call last):
        ...
    TypeError: Not a Number
    >>> compute_geometric_mean(5, 125)
    25.0
    >>> compute_geometric_mean(1, 0)
    0.0
    >>> compute_geometric_mean(1, 5, 25, 5)
    5.0
    >>> compute_geometric_mean(2, -2)
    Traceback (most recent call last):
        ...
    ArithmeticError: Cannot Compute Geometric Mean for these numbers.
    >>> compute_geometric_mean(-5, 25, 1)
    -5.0
    """
    product = 1
    for number in args:
        if (not isinstance(number, int)) and (not isinstance(number, float)):
            raise TypeError("Not a Number")
        product *= number
    # Cannot calculate the even root for negative product.
    # Frequently they are restricted to being positive.
    if product < 0 and len(args) % 2 == 0:
        raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.")
    mean = abs(product) ** (1.0 / len(args))
    # Since python calculates complex roots for negative products with odd roots.
    if product < 0:
        mean = -mean
    # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996
    possible_mean = float(round(mean))
    # To check if the rounded number is actually the mean.
    if possible_mean ** len(args) == product:
        mean = possible_mean
    return mean


if __name__ == "__main__":
    from doctest import testmod

    testmod(name="compute_geometric_mean")
    print(compute_geometric_mean(-3, -27))


Review comment (suggestion):
```suggestion
    mean = abs(product) ** (1 / len(args))
```

Code after:
    Traceback (most recent call last):
        ...
    TypeError: Not a Number
    >>> compute_geometric_mean(5, 125)
    25.0
    >>> compute_geometric_mean(1, 0)
    0.0
    >>> compute_geometric_mean(1, 5, 25, 5)
    5.0
    >>> compute_geometric_mean(2, -2)
    Traceback (most recent call last):
        ...
    ArithmeticError: Cannot Compute Geometric Mean for these numbers.
    >>> compute_geometric_mean(-5, 25, 1)
    -5.0
    """
    product = 1
    for number in args:
        if not isinstance(number, int) and not isinstance(number, float):
            raise TypeError("Not a Number")
        product *= number
    # Cannot calculate the even root for negative product.
    # Frequently they are restricted to being positive.
    if product < 0 and len(args) % 2 == 0:
        raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.")
    mean = abs(product) ** (1 / len(args))
    # Since python calculates complex roots for negative products with odd roots.
    if product < 0:
        mean = -mean
    # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996
    possible_mean = float(round(mean))
    # To check if the rounded number is actually the mean.
    if possible_mean ** len(args) == product:
        mean = possible_mean
    return mean


if __name__ == "__main__":
    from doctest import testmod

    testmod(name="compute_geometric_mean")
    print(compute_geometric_mean(-3, -27))
Repository: TheAlgorithms/Python
File: data_structures/stacks/stock_span_problem.py (Python)

Code before:
"""
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.

The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
"""


def calculation_span(price):
    """
    Calculate the span values for a given list of stock prices.
    Args:
        price (list): List of stock prices.
    Returns:
    >>> price = [10, 4, 5, 90, 120, 80]
    >>> calculation_span(price)
    [1, 1, 2, 4, 5, 6]
    >>> price = [100, 50, 60, 70, 80, 90]
    >>> calculation_span(price)
    [1, 1, 2, 3, 4, 5]
    >>> price = [5, 4, 3, 2, 1]
    >>> calculation_span(price)
    [1, 1, 2, 3, 4]
    >>> price = [1, 2, 3, 4, 5]
    >>> calculation_span(price)
    [1, 2, 3, 4, 5]
    >>> price = [10, 20, 30, 40, 50]
    >>> calculation_span(price)
    [1, 2, 3, 4, 5]
    """
    n = len(price)
    st = [0]
    s = [0] * n
    s[0] = 1

Review comment (suggestion):
```suggestion
def calculation_span(price: list[int]):
```
Or even better `list[float]`

Code after:
"""
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.

The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
"""


def calculate_span(price: list[int]) -> list[int]:
    """
    Calculate the span values for a given list of stock prices.
    Args:
        price: List of stock prices.
    Returns:
        List of span values.

    >>> calculate_span([10, 4, 5, 90, 120, 80])
    [1, 1, 2, 4, 5, 1]
    >>> calculate_span([100, 50, 60, 70, 80, 90])
    [1, 1, 2, 3, 4, 5]
    >>> calculate_span([5, 4, 3, 2, 1])
    [1, 1, 1, 1, 1]
    >>> calculate_span([1, 2, 3, 4, 5])
    [1, 2, 3, 4, 5]
    >>> calculate_span([10, 20, 30, 40, 50])
    [1, 2, 3, 4, 5]
    >>> calculate_span([100, 80, 60, 70, 60, 75, 85])
    [1, 1, 1, 2, 1, 4, 6]
    """
    n = len(price)
    s = [0] * n
    # Create a stack and push index of fist element to it
    st = []
    st.append(0)
Repository: TheAlgorithms/Python
File: data_structures/stacks/stock_span_problem.py (Python)

Code before:
"""
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.

The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
"""


def calculation_span(price: list[float]):
    """
    Calculate the span values for a given list of stock prices.
    Args:
        price (list): List of stock prices.
    Returns:
    >>> price = [10, 4, 5, 90, 120, 80]
    >>> calculation_span(price)
    [1, 1, 2, 4, 5, 6]
    >>> price = [100, 50, 60, 70, 80, 90]
    >>> calculation_span(price)
    [1, 1, 2, 3, 4, 5]
    >>> price = [5, 4, 3, 2, 1]
    >>> calculation_span(price)
    [1, 1, 2, 3, 4]
    >>> price = [1, 2, 3, 4, 5]
    >>> calculation_span(price)
    [1, 2, 3, 4, 5]
    >>> price = [10, 20, 30, 40, 50]
    >>> calculation_span(price)
    [1, 2, 3, 4, 5]
    """
    n = len(price)
    st = [0]
    s = [0] * n
    s[0] = 1

Review comment (suggestion):
```suggestion
def calculation_span(price: list[float]) -> list[float]:
```

Code after:
"""
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.

The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
"""


def calculate_span(price: list[int]) -> list[int]:
    """
    Calculate the span values for a given list of stock prices.
    Args:
        price: List of stock prices.
    Returns:
        List of span values.

    >>> calculate_span([10, 4, 5, 90, 120, 80])
    [1, 1, 2, 4, 5, 1]
    >>> calculate_span([100, 50, 60, 70, 80, 90])
    [1, 1, 2, 3, 4, 5]
    >>> calculate_span([5, 4, 3, 2, 1])
    [1, 1, 1, 1, 1]
    >>> calculate_span([1, 2, 3, 4, 5])
    [1, 2, 3, 4, 5]
    >>> calculate_span([10, 20, 30, 40, 50])
    [1, 2, 3, 4, 5]
    >>> calculate_span([100, 80, 60, 70, 60, 75, 85])
    [1, 1, 1, 2, 1, 4, 6]
    """
    n = len(price)
    s = [0] * n
    # Create a stack and push index of fist element to it
    st = []
    st.append(0)
Repository: TheAlgorithms/Python
File: maths/trapezoidal_rule.py (Python)

Code before:
"""
Numerical integration or quadrature for a smooth function f with known values at x_i

This method is the classical approach of summing 'Equally Spaced Abscissas'

Method 1:
"Extended Trapezoidal Rule"

"""


def method_1(boundary, steps):
    """
    This function implements the extended trapezoidal rule for numerical integration.
    The function f(x) is provided below.

    :param boundary: List containing the lower and upper bounds of integration [a, b]
    :param steps: The number of steps (intervals) used in the approximation
    :return: The numerical approximation of the integral

    >>> abs(method_1([0, 1], 10) - 0.33333) < 0.01
    True

    >>> abs(method_1([0, 1], 100) - 0.33333) < 0.01
    True

    >>> abs(method_1([0, 2], 1000) - 2.66667) < 0.01
    True

    >>> abs(method_1([1, 2], 1000) - 2.33333) < 0.01
    True
    """
    h = (boundary[1] - boundary[0]) / steps
    a = boundary[0]
    b = boundary[1]
    x_i = make_points(a, b, h)
    y = 0.0

Review comment (suggestion):
```suggestion
def trapezoidal_rule(boundary, steps):
```
Let's rename the function to something more descriptive. I'm not sure why the code calls it "method 1" when there's only one method in the file.

Code after:
"""
Numerical integration or quadrature for a smooth function f with known values at x_i
"""


def trapezoidal_rule(boundary, steps):
    """
    Implements the extended trapezoidal rule for numerical integration.
    The function f(x) is provided below.

    :param boundary: List containing the lower and upper bounds of integration [a, b]
    :param steps: The number of steps (intervals) used in the approximation
    :return: The numerical approximation of the integral

    >>> abs(trapezoidal_rule([0, 1], 10) - 0.33333) < 0.01
    True
    >>> abs(trapezoidal_rule([0, 1], 100) - 0.33333) < 0.01
    True
    >>> abs(trapezoidal_rule([0, 2], 1000) - 2.66667) < 0.01
    True
    >>> abs(trapezoidal_rule([1, 2], 1000) - 2.33333) < 0.01
    True
    """
    h = (boundary[1] - boundary[0]) / steps
    a = boundary[0]
    b = boundary[1]
    x_i = make_points(a, b, h)
    y = 0.0
    y += (h / 2.0) * f(a)
    for i in x_i:
        y += h * f(i)
    y += (h / 2.0) * f(b)
    return y


def make_points(a, b, h):
    """
Repository: TheAlgorithms/Python
File: maths/trapezoidal_rule.py (Python)

Code before:
"""
Numerical integration or quadrature for a smooth function f with known values at x_i

This method is the classical approach of summing 'Equally Spaced Abscissas'

Method 1:
"Extended Trapezoidal Rule"

"""


def method_1(boundary, steps):
    """
    This function implements the extended trapezoidal rule for numerical integration.
    The function f(x) is provided below.

    :param boundary: List containing the lower and upper bounds of integration [a, b]
    :param steps: The number of steps (intervals) used in the approximation
    :return: The numerical approximation of the integral

    >>> abs(method_1([0, 1], 10) - 0.33333) < 0.01
    True

    >>> abs(method_1([0, 1], 100) - 0.33333) < 0.01
    True

    >>> abs(method_1([0, 2], 1000) - 2.66667) < 0.01
    True


Review comment (security):
```suggestion
The trapezoidal rule is the classical approach of summing 'Equally Spaced Abscissas'
```
Let's rephrase the header docstring to name the rule directly. I'm not sure why the original author called it "method 1".

Code after:
"""
Numerical integration or quadrature for a smooth function f with known values at x_i
"""


def trapezoidal_rule(boundary, steps):
    """
    Implements the extended trapezoidal rule for numerical integration.
    The function f(x) is provided below.

    :param boundary: List containing the lower and upper bounds of integration [a, b]
    :param steps: The number of steps (intervals) used in the approximation
    :return: The numerical approximation of the integral

    >>> abs(trapezoidal_rule([0, 1], 10) - 0.33333) < 0.01
    True
    >>> abs(trapezoidal_rule([0, 1], 100) - 0.33333) < 0.01
    True
    >>> abs(trapezoidal_rule([0, 2], 1000) - 2.66667) < 0.01
    True
    >>> abs(trapezoidal_rule([1, 2], 1000) - 2.33333) < 0.01
    True
    """
    h = (boundary[1] - boundary[0]) / steps
    a = boundary[0]
    b = boundary[1]
    x_i = make_points(a, b, h)
    y = 0.0
    y += (h / 2.0) * f(a)
Repository: TheAlgorithms/Python
File: conversions/rectangular_to_polar.py (Python)

Code before:
import math


def rectangular_to_polar(real: float, img: float) -> tuple[float, float]:
    """
    https://en.wikipedia.org/wiki/Polar_coordinate_system

    >>> rec_to_pol(5,-5)
    (7.07, -45.0)
    >>> rec_to_pol(-1,1)
    (1.41, 135.0)
    >>> rec_to_pol(-1,-1)
    (1.41, -135.0)
    >>> rec_to_pol(1e-10,1e-10)
    (0.0, 45.0)
    >>> rec_to_pol(-1e-10,1e-10)
    (0.0, 135.0)
    >>> rec_to_pol(9.75,5.93)
    (11.41, 31.31)
    >>> rec_to_pol(10000,99999)
    (100497.76, 84.29)
    """

    mod = round(math.sqrt((real**2) + (img**2)), 2)
    ang = round(math.degrees(math.atan2(img, real)), 2)
    return (mod, ang)


if __name__ == "__main__":
    import doctest

    doctest.testmod()


Review comment (suggestion):
```suggestion
    >>> rectangular_to_polar(5,-5)
    (7.07, -45.0)
    >>> rectangular_to_polar(-1,1)
    (1.41, 135.0)
    >>> rectangular_to_polar(-1,-1)
    (1.41, -135.0)
    >>> rectangular_to_polar(1e-10,1e-10)
    (0.0, 45.0)
    >>> rectangular_to_polar(-1e-10,1e-10)
    (0.0, 135.0)
    >>> rectangular_to_polar(9.75,5.93)
    (11.41, 31.31)
    >>> rectangular_to_polar(10000,99999)
```

Code after:
import math


def rectangular_to_polar(real: float, img: float) -> tuple[float, float]:
    """
    https://en.wikipedia.org/wiki/Polar_coordinate_system

    >>> rectangular_to_polar(5,-5)
    (7.07, -45.0)
    >>> rectangular_to_polar(-1,1)
    (1.41, 135.0)
    >>> rectangular_to_polar(-1,-1)
    (1.41, -135.0)
    >>> rectangular_to_polar(1e-10,1e-10)
    (0.0, 45.0)
    >>> rectangular_to_polar(-1e-10,1e-10)
    (0.0, 135.0)
    >>> rectangular_to_polar(9.75,5.93)
    (11.41, 31.31)
    >>> rectangular_to_polar(10000,99999)
    (100497.76, 84.29)
    """

    mod = round(math.sqrt((real**2) + (img**2)), 2)
    ang = round(math.degrees(math.atan2(img, real)), 2)
    return (mod, ang)


if __name__ == "__main__":
    import doctest

    doctest.testmod()