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

Issue:
errors in balanced_parentheses.py
https://github.com/TheAlgorithms/Python/blob/6a95bf9ad8090a1280abf76752a52ab9ee2420b7/data_structures/stacks/balanced_parentheses.py#L13-L17

`Line 16` returns wrong result due to `not`

`Line 15` can cause error for inputs like **))**. before calling _pop_ it should be checked if stack is empty.

https://github.com/TheAlgorithms/Python/blob/6a95bf9ad8090a1280abf76752a52ab9ee2420b7/data_structures/stacks/balanced_parentheses.py#L3

there is no module named **.Stack**. it should be
 _from **s**tack import Stack_


Discussion:

Resolving patch:
diff --git a/data_structures/stacks/balanced_parentheses.py b/data_structures/stacks/balanced_parentheses.py
--- a/data_structures/stacks/balanced_parentheses.py
+++ b/data_structures/stacks/balanced_parentheses.py
@@ -1,6 +1,6 @@
 from __future__ import print_function
 from __future__ import absolute_import
-from .Stack import Stack
+from stack import Stack
 
 __author__ = 'Omkar Pathak'
 
@@ -12,12 +12,14 @@ def balanced_parentheses(parentheses):
         if parenthesis == '(':
             stack.push(parenthesis)
         elif parenthesis == ')':
+            if stack.is_empty():
+                return False
             stack.pop()
-    return not stack.is_empty()
+    return stack.is_empty()
 
 
 if __name__ == '__main__':
-    examples = ['((()))', '((())']
+    examples = ['((()))', '((())', '(()))']
     print('Balanced parentheses demonstration:\n')
     for example in examples:
         print(example + ': ' + str(balanced_parentheses(example)))


Test patch:
Repository: TheAlgorithms/Python

Issue:
math CheckPrime is wrong
The current implementation doesn't support:

* Negative values, -1 is not a prime number. Current implementation raise a TypeError due to `math.sqrt` on negative values.

The current implementation return the wrong value for:

* 0, 0 doesn't have any divider, primes must have two.
* 1, 1 just have one divider, primes must have two.


Discussion:

Resolving patch:
diff --git a/maths/PrimeCheck.py b/maths/PrimeCheck.py
--- a/maths/PrimeCheck.py
+++ b/maths/PrimeCheck.py
@@ -1,13 +1,54 @@
 import math
+import unittest
+
+
 def primeCheck(number):
-    if number % 2 == 0 and number > 2: 
+    """
+    A number is prime if it has exactly two dividers: 1 and itself.
+    """
+    if number < 2:
+        # Negatives, 0 and 1 are not primes
         return False
-    return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))
+    if number < 4:
+        # 2 and 3 are primes
+        return True
+    if number % 2 == 0:
+        # Even values are not primes
+        return False
+
+    # Except 2, all primes are odd. If any odd value divide
+    # the number, then that number is not prime.
+    odd_numbers = range(3, int(math.sqrt(number)) + 1, 2)
+    return not any(number % i == 0 for i in odd_numbers)
+
+
+class Test(unittest.TestCase):
+    def test_primes(self):
+        self.assertTrue(primeCheck(2))
+        self.assertTrue(primeCheck(3))
+        self.assertTrue(primeCheck(5))
+        self.assertTrue(primeCheck(7))
+        self.assertTrue(primeCheck(11))
+        self.assertTrue(primeCheck(13))
+        self.assertTrue(primeCheck(17))
+        self.assertTrue(primeCheck(19))
+        self.assertTrue(primeCheck(23))
+        self.assertTrue(primeCheck(29))
+
+    def test_not_primes(self):
+        self.assertFalse(primeCheck(-19),
+                "Negative numbers are not prime.")
+        self.assertFalse(primeCheck(0),
+                "Zero doesn't have any divider, primes must have two")
+        self.assertFalse(primeCheck(1),
+                "One just have 1 divider, primes must have two.")
+        self.assertFalse(primeCheck(2 * 2))
+        self.assertFalse(primeCheck(2 * 3))
+        self.assertFalse(primeCheck(3 * 3))
+        self.assertFalse(primeCheck(3 * 5))
+        self.assertFalse(primeCheck(3 * 5 * 7))
 
-def main():
-    print(primeCheck(37))
-    print(primeCheck(100))
-    print(primeCheck(77))
 
 if __name__ == '__main__':
-	main()
+    unittest.main()
+


Test patch:
Repository: TheAlgorithms/Python

Issue:
Travis CI: Add flake8-filename to our testing
@Alfro As discussed at https://github.com/TheAlgorithms/Python/pull/993#issuecomment-510141457


Discussion:

Resolving patch:
diff --git a/scripts/validate_filenames.py b/scripts/validate_filenames.py
new file mode 100755
--- /dev/null
+++ b/scripts/validate_filenames.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+
+import os
+from build_directory_md import good_filepaths
+
+filepaths = list(good_filepaths())
+assert filepaths, "good_filepaths() failed!"
+
+
+upper_files = [file for file in filepaths if file != file.lower()]
+if upper_files:
+    print(f"{len(upper_files)} files contain uppercase characters:")
+    print("\n".join(upper_files) + "\n")
+
+space_files = [file for file in filepaths if " " in file]
+if space_files:
+    print(f"{len(space_files)} files contain space characters:")
+    print("\n".join(space_files) + "\n")
+
+nodir_files = [file for file in filepaths if os.sep not in file]
+if nodir_files:
+    print(f"{len(nodir_files)} files are not in a directory:")
+    print("\n".join(nodir_files) + "\n")
+
+bad_files = len(upper_files + space_files + nodir_files)
+if bad_files:
+    import sys
+    sys.exit(bad_files)


Test patch:
Repository: TheAlgorithms/Python

Issue:
decimal_to_binary() should return identical values as bin()
https://github.com/TheAlgorithms/Python/blob/7b267e5e4f8ccb72dd58fcf0057642fd62a36bdf/conversions/decimal_to_binary.py#L4

Please change __decimal_to_binary()__ to return identical values as the Python builtin [__bin()__](https://docs.python.org/3/library/functions.html#bin).  With doctests to prove it please.

@PatOnTheBack @Corruption13


Discussion:
Give an example of a decimal number for which `decimal_to_binary(num)` is inconsistent.
__0b__ is missing

Resolving patch:
diff --git a/conversions/decimal_to_binary.py b/conversions/decimal_to_binary.py
--- a/conversions/decimal_to_binary.py
+++ b/conversions/decimal_to_binary.py
@@ -2,24 +2,57 @@
 
 
 def decimal_to_binary(num):
-    """Convert a Decimal Number to a Binary Number."""
+
+    """
+        Convert a Integer Decimal Number to a Binary Number as str.
+        >>> decimal_to_binary(0)
+        '0b0'
+        >>> decimal_to_binary(2)
+        '0b10'
+        >>> decimal_to_binary(7)
+        '0b111'
+        >>> decimal_to_binary(35)
+        '0b100011'
+        >>> # negatives work too
+        >>> decimal_to_binary(-2)
+        '-0b10'
+        >>> # other floats will error
+        >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
+        Traceback (most recent call last):
+        ...
+        TypeError: 'float' object cannot be interpreted as an integer
+        >>> # strings will error as well
+        >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
+        Traceback (most recent call last):
+        ...
+        TypeError: 'str' object cannot be interpreted as an integer
+    """
+
+    if type(num) == float:
+        raise TypeError("'float' object cannot be interpreted as an integer")
+    if type(num) == str:
+        raise TypeError("'str' object cannot be interpreted as an integer")
+
+    if num == 0:
+        return "0b0"
+
+    negative = False
+
+    if num < 0:
+        negative = True
+        num = -num
+
     binary = []
     while num > 0:
         binary.insert(0, num % 2)
         num >>= 1
-    return "".join(str(e) for e in binary)
 
+    if negative:
+        return "-0b" + "".join(str(e) for e in binary)
 
-def main():
-    """Print binary equivelents of decimal numbers."""
-    print("\n2 in binary is:")
-    print(decimal_to_binary(2))  # = 10
-    print("\n7 in binary is:")
-    print(decimal_to_binary(7))  # = 111
-    print("\n35 in binary is:")
-    print(decimal_to_binary(35))  # = 100011
-    print("\n")
+    return "0b" + "".join(str(e) for e in binary)
 
 
-if __name__ == '__main__':
-    main()
+if __name__ == "__main__":
+    import doctest
+    doctest.testmod()


Test patch:
Repository: TheAlgorithms/Python

Issue:
file_transfer_protocol doesn't actually implement FTP
It simply sends the contents of a single file over a TCP socket, with no support for browsing directories, or authentication. While this is a good demo of how to setup and use TCP sockets in Python, it is not really an implementation of FTP.


Discussion:
What would be a better, less misleading title for these files?
send_data.py?
send_file.py and receive_file.py ?
send_a_file.py and receive_a_file.py ?

Please consider submitting a PR.
sure, `send_file.py` and `receive_file.py` sounds good

Resolving patch:
diff --git a/file_transfer_protocol/client.py b/file_transfer_protocol/recieve_file.py
similarity index 100%
rename from file_transfer_protocol/client.py
rename to file_transfer_protocol/recieve_file.py
diff --git a/file_transfer_protocol/server.py b/file_transfer_protocol/send_file.py
similarity index 100%
rename from file_transfer_protocol/server.py
rename to file_transfer_protocol/send_file.py


Test patch:
Repository: TheAlgorithms/Python

Issue:
DIRECTORY.md not being updated by TravisCI
- [x] .travis.yml isn't updating DIRECTORY.md automatically as it should
- [x] scripts/build_directory_md.py needs can have some minor changes too.  #1461


Discussion:

Resolving patch:
diff --git a/scripts/build_directory_md.py b/scripts/build_directory_md.py
--- a/scripts/build_directory_md.py
+++ b/scripts/build_directory_md.py
@@ -17,7 +17,7 @@ def good_filepaths(top_dir: str = ".") -> Iterator[str]:
 
 
 def md_prefix(i):
-    return f"{i * '  '}*" if i else "##"
+    return f"{i * '  '}*" if i else "\n##"
 
 
 def print_path(old_path: str, new_path: str) -> str:
@@ -37,7 +37,7 @@ def print_directory_md(top_dir: str = ".") -> None:
             old_path = print_path(old_path, filepath)
         indent = (filepath.count(os.sep) + 1) if filepath else 0
         url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
-        filename = os.path.splitext(filename.replace("_", " "))[0]
+        filename = os.path.splitext(filename.replace("_", " ").title())[0]
         print(f"{md_prefix(indent)} [{filename}]({url})")
 
 


Test patch:
Repository: TheAlgorithms/Python

Issue:
Type Error in linear_discriminant_analysis.py
There is a type error in this following code:
`pre_indexes = predict_y_values(x, actual_means, variance, probabilities)`
the 'probabilities' parameter must be a list object , but is a generator object.
generated error is as follows:
`TypeError: 'generator' object is not subscriptable`


Discussion:

Resolving patch:
diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py
--- a/machine_learning/linear_discriminant_analysis.py
+++ b/machine_learning/linear_discriminant_analysis.py
@@ -295,10 +295,10 @@ def main():
         print("-" * 100)
 
         # Calculating the value of probabilities for each class
-        # An empty list to store values of probabilities for each class
-        probabilities = (
+        probabilities = [
             calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes)
-        )
+        ]
+
         # for loop iterates over number of elements in 'probabilities' list and print
         # out them in separated line
         for i, probability in enumerate(probabilities, 1):


Test patch:
Repository: TheAlgorithms/Python

Issue:
Same name for an attribute and a function
Hi, I'm new to programming and I'm not sure if it's a problem, but the code(
Python/data_structures/queue/queue_on_list.py) have the same name for an attribute and a function.
```
class Queue:
    def __init__(self):
        self.entries = []
        self.length = 0
        self.front = 0

    def front(self):
        return self.entries[0]
```
When executed it gives me the error:
TypeError: 'int' object is not callable


Discussion:
You are correct.  It is an anti-pattern to have the same name for both an attribute and a method of the same class.
@cclauss  , can I work on this ?

Resolving patch:
diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py
--- a/data_structures/queue/queue_on_list.py
+++ b/data_structures/queue/queue_on_list.py
@@ -43,7 +43,7 @@ def rotate(self, rotation):
     """Enqueues {@code item}
     @return item at front of self.entries"""
 
-    def front(self):
+    def get_front(self):
         return self.entries[0]
 
     """Returns the length of this.entries"""


Test patch:
Repository: TheAlgorithms/Python

Issue:
Doctests failing maths/bailey_borwein_plouffe.py
Doctests are failing in https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py

```
________ [doctest] maths.bailey_borwein_plouffe.bailey_borwein_plouffe _________
021     ValueError: Digit position must be a positive integer
022     >>> bailey_borwein_plouffe(0)
023     Traceback (most recent call last):
024       ...
025     ValueError: Digit position must be a positive integer
026     >>> bailey_borwein_plouffe(1.7)
027     Traceback (most recent call last):
028       ...
029     ValueError: Digit position must be a positive integer
030     >>> bailey_borwein_plouffe(2, -10)
Differences (unified diff with -expected +actual):
    @@ -1,3 +1,8 @@
     Traceback (most recent call last):
    -  ...
    -ValueError: Precision must be a nonnegative integer
    +  File "/opt/python/3.8.1/lib/python3.8/doctest.py", line 1329, in __run
    +    exec(compile(example.source, filename, "single",
    +  File "<doctest maths.bailey_borwein_plouffe.bailey_borwein_plouffe[5]>", line 1, in <module>
    +    bailey_borwein_plouffe(2, -10)
    +  File "/home/travis/build/TheAlgorithms/Python/maths/bailey_borwein_plouffe.py", line 42, in bailey_borwein_plouffe
    +    raise ValueError("Please input a nonnegative integer for the precision")
    +ValueError: Please input a nonnegative integer for the precision
```
Source: https://travis-ci.com/github/TheAlgorithms/Python/builds/166844585


Discussion:

Resolving patch:
diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py
--- a/data_structures/linked_list/singly_linked_list.py
+++ b/data_structures/linked_list/singly_linked_list.py
@@ -106,7 +106,7 @@ def __setitem__(self, index, data):
                 raise IndexError("Index out of range.")
             current = current.next
         current.data = data
-       
+
     def __len__(self):
         """
         Return length of linked list i.e. number of nodes
diff --git a/maths/bailey_borwein_plouffe.py b/maths/bailey_borwein_plouffe.py
--- a/maths/bailey_borwein_plouffe.py
+++ b/maths/bailey_borwein_plouffe.py
@@ -39,7 +39,7 @@ def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str:
     if (not isinstance(digit_position, int)) or (digit_position <= 0):
         raise ValueError("Digit position must be a positive integer")
     elif (not isinstance(precision, int)) or (precision < 0):
-        raise ValueError("Please input a nonnegative integer for the precision")
+        raise ValueError("Precision must be a nonnegative integer")
 
     # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly accurate
     sum_result = (


Test patch:
Repository: TheAlgorithms/Python

Issue:
Mergesort Update Variable Names
I was looking over the mergesort.py file in the divide_and_conquer directory when I saw that all of the variable names are a single letter and there is not much documentation. Does anyone know enough about this file to improve the variable names and make the code more understandable?


Discussion:
Can I improve the file?
No need to wait for permission.  Just go for it.  Pull requests will be reviewed.

Only our competitors think that we should wait.
Can I Modify the Variables to Clarify There Meanings ?
What I can do
Hello folks @Robinson-Arivan @aditya-190 @avitomar12, welcome to the community and before you contribute, please read our [CONTRIBUTION.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). It resolves most of the doubts you may have! You can go to the file and see if there's a problem as OP has noted. If you want to take the issue, remember to notify our community here as well to avoid conflicts.

Resolving patch:
diff --git a/divide_and_conquer/mergesort.py b/divide_and_conquer/mergesort.py
--- a/divide_and_conquer/mergesort.py
+++ b/divide_and_conquer/mergesort.py
@@ -1,45 +1,48 @@
-def merge(a, b, m, e):
-    l = a[b : m + 1]  # noqa: E741
-    r = a[m + 1 : e + 1]
-    k = b
+def merge(arr, left, mid, right):
+    # overall array will divided into 2 array
+    # left_arr contains the left portion of array from left to mid
+    # right_arr contains the right portion of array from mid + 1 to right
+    left_arr = arr[left : mid + 1]
+    right_arr = arr[mid + 1 : right + 1]
+    k = left
     i = 0
     j = 0
-    while i < len(l) and j < len(r):
+    while i < len(left_arr) and j < len(right_arr):
         # change sign for Descending order
-        if l[i] < r[j]:
-            a[k] = l[i]
+        if left_arr[i] < right_arr[j]:
+            arr[k] = left_arr[i]
             i += 1
         else:
-            a[k] = r[j]
+            arr[k] = right_arr[j]
             j += 1
         k += 1
-    while i < len(l):
-        a[k] = l[i]
+    while i < len(left_arr):
+        arr[k] = left_arr[i]
         i += 1
         k += 1
-    while j < len(r):
-        a[k] = r[j]
+    while j < len(right_arr):
+        arr[k] = right_arr[j]
         j += 1
         k += 1
-    return a
+    return arr
 
 
-def mergesort(a, b, e):
+def mergesort(arr, left, right):
     """
-    >>> mergesort([3,2,1],0,2)
+    >>> mergesort([3, 2, 1], 0, 2)
     [1, 2, 3]
-    >>> mergesort([3,2,1,0,1,2,3,5,4],0,8)
+    >>> mergesort([3, 2, 1, 0, 1, 2, 3, 5, 4], 0, 8)
     [0, 1, 1, 2, 2, 3, 3, 4, 5]
     """
-    if b < e:
-        m = (b + e) // 2
+    if left < right:
+        mid = (left + right) // 2
         # print("ms1",a,b,m)
-        mergesort(a, b, m)
+        mergesort(arr, left, mid)
         # print("ms2",a,m+1,e)
-        mergesort(a, m + 1, e)
+        mergesort(arr, mid + 1, right)
         # print("m",a,b,m,e)
-        merge(a, b, m, e)
-        return a
+        merge(arr, left, mid, right)
+        return arr
 
 
 if __name__ == "__main__":


Test patch:
Repository: TheAlgorithms/Python

Issue:
Add Python type hints and doctests to other/two_sum.py
@tonydelanuez Would you be willing to add Python type hints and doctests to [`other/two_sum.py`](../blob/master/other/two_sum.py)?  The function comments say that it will return a `list[int]` but instead it either returns a `list[list[int]]` or `False`.


Discussion:

Resolving patch:
diff --git a/other/two_sum.py b/other/two_sum.py
--- a/other/two_sum.py
+++ b/other/two_sum.py
@@ -11,21 +11,37 @@
 Because nums[0] + nums[1] = 2 + 7 = 9,
 return [0, 1].
 """
+from __future__ import annotations
 
 
-def twoSum(nums, target):
+def two_sum(nums: list[int], target: int) -> list[int]:
     """
-    :type nums: List[int]
-    :type target: int
-    :rtype: List[int]
+    >>> two_sum([2, 7, 11, 15], 9)
+    [0, 1]
+    >>> two_sum([15, 2, 11, 7], 13)
+    [1, 2]
+    >>> two_sum([2, 7, 11, 15], 17)
+    [0, 3]
+    >>> two_sum([7, 15, 11, 2], 18)
+    [0, 2]
+    >>> two_sum([2, 7, 11, 15], 26)
+    [2, 3]
+    >>> two_sum([2, 7, 11, 15], 8)
+    []
+    >>> two_sum([3 * i for i in range(10)], 19)
+    []
     """
     chk_map = {}
     for index, val in enumerate(nums):
         compl = target - val
         if compl in chk_map:
-            indices = [chk_map[compl], index]
-            print(indices)
-            return [indices]
-        else:
-            chk_map[val] = index
-    return False
+            return [chk_map[compl], index]
+        chk_map[val] = index
+    return []
+
+
+if __name__ == "__main__":
+    import doctest
+
+    doctest.testmod()
+    print(f"{two_sum([2, 7, 11, 15], 9) = }")


Test patch:
Repository: TheAlgorithms/Python

Issue:
Add more solutions to Project Euler problems
Project Euler has about 700 problems, but the current repository hosts solutions for only about 60-70 problems.   
I'm willing to work on the issue and also if someone wants to help they can join in.  
We can create guidelines on how many minimum solutions a PR should have to prevent spammy PRs with just one or two easy solutions. (open to discussion)


Discussion:

Resolving patch:
diff --git a/project_euler/problem_71/__init__.py b/project_euler/problem_71/__init__.py
new file mode 100644
diff --git a/project_euler/problem_71/sol1.py b/project_euler/problem_71/sol1.py
new file mode 100644
--- /dev/null
+++ b/project_euler/problem_71/sol1.py
@@ -0,0 +1,48 @@
+"""
+Ordered fractions
+Problem 71
+https://projecteuler.net/problem=71
+
+Consider the fraction n/d, where n and d are positive
+integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
+
+If we list the set of reduced proper fractions for d ≤ 8
+in ascending order of size, we get:
+    1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7,
+    1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
+
+It can be seen that 2/5 is the fraction immediately to the left of 3/7.
+
+By listing the set of reduced proper fractions for d ≤ 1,000,000
+in ascending order of size, find the numerator of the fraction
+immediately to the left of 3/7.
+"""
+
+
+def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int:
+    """
+    Returns the closest numerator of the fraction immediately to the
+    left of given fraction (numerator/denominator) from a list of reduced
+    proper fractions.
+    >>> solution()
+    428570
+    >>> solution(3, 7, 8)
+    2
+    >>> solution(6, 7, 60)
+    47
+    """
+    max_numerator = 0
+    max_denominator = 1
+
+    for current_denominator in range(1, limit + 1):
+        current_numerator = current_denominator * numerator // denominator
+        if current_denominator % denominator == 0:
+            current_numerator -= 1
+        if current_numerator * max_denominator > current_denominator * max_numerator:
+            max_numerator = current_numerator
+            max_denominator = current_denominator
+    return max_numerator
+
+
+if __name__ == "__main__":
+    print(solution(numerator=3, denominator=7, limit=1000000))


Test patch:
Repository: TheAlgorithms/Python

Issue:
Unable to move the file "other/words"
I wanted to move the files "other/anagrams.py" and "other/words" to the string-folder to make them easier to find. But I can't move the file "other/words" since it has "contains an invalid extension" according to algorithms-keeper. I left the file "other/anagrams.py" in the other-folder for now since it seems to depend on "other/words".


Discussion:
That seems like a `.txt` file and as that file does not contain any extension, the bot will not be able to infer it. If possible, can you please update the file name to include the extension in your open pull request?
Thanks for the insight, I'll give it a try once I have the time.

Resolving patch:
diff --git a/other/anagrams.py b/strings/anagrams.py
similarity index 95%
rename from other/anagrams.py
rename to strings/anagrams.py
--- a/other/anagrams.py
+++ b/strings/anagrams.py
@@ -6,7 +6,7 @@
 start_time = time.time()
 print("creating word list...")
 path = os.path.split(os.path.realpath(__file__))
-with open(path[0] + "/words") as f:
+with open(path[0] + "/words.txt") as f:
     word_list = sorted(list({word.strip().lower() for word in f}))
 
 


Test patch: