diff --git a/src/llm_benchmark/algorithms/primes.py b/src/llm_benchmark/algorithms/primes.py index 9c56daa..dca974f 100644 --- a/src/llm_benchmark/algorithms/primes.py +++ b/src/llm_benchmark/algorithms/primes.py @@ -12,11 +12,17 @@ def is_prime(n: int) -> bool: Returns: bool: True if the number is prime, False otherwise """ - if n < 2: + if n <= 1: return False - for i in range(2, n): - if n % i == 0: + if n <= 3: + return True + if n % 2 == 0 or n % 3 == 0: + return False + i = 5 + while i * i <= n: + if n % i == 0 or n % (i + 2) == 0: return False + i += 6 return True @staticmethod @@ -29,9 +35,18 @@ def sum_primes(n: int) -> int: Returns: int: Sum of primes from 0 to n """ + if n <= 1: + return 0 + primes = [True] * n + p = 2 + while p * p <= n: + if primes[p]: + for i in range(p * p, n, p): + primes[i] = False + p += 1 sum_ = 0 - for i in range(n): - if Primes.is_prime(i): + for i in range(2, n): + if primes[i]: sum_ += i return sum_ @@ -46,10 +61,12 @@ def prime_factors(n: int) -> List[int]: List[int]: List of prime factors """ ret = [] - while n > 1: - for i in range(2, n + 1): - if n % i == 0: - ret.append(i) - n = n // i - break - return ret + i = 2 + while i * i <= n: + while n % i == 0: + ret.append(i) + n //= i + i += 1 + if n > 1: + ret.append(n) + return ret \ No newline at end of file diff --git a/src/llm_benchmark/algorithms/sort.py b/src/llm_benchmark/algorithms/sort.py index 5f36289..5e133f4 100644 --- a/src/llm_benchmark/algorithms/sort.py +++ b/src/llm_benchmark/algorithms/sort.py @@ -1,59 +1,26 @@ from sys import maxsize from typing import List - +import heapq class Sort: @staticmethod def sort_list(v: List[int]) -> None: - """Sort a list of integers in place - - Args: - v (List[int]): List of integers - """ - for i in range(len(v)): - for j in range(i + 1, len(v)): - if v[i] > v[j]: - v[i], v[j] = v[j], v[i] + v.sort() @staticmethod def dutch_flag_partition(v: List[int], pivot_value: int) -> None: - """Dutch flag partitioning - - Args: - v (List[int]): List of integers - pivot_value (int): Pivot value - """ - next_value = 0 - - for i in range(len(v)): - if v[i] < pivot_value: - v[i], v[next_value] = v[next_value], v[i] - next_value += 1 - for i in range(next_value, len(v)): - if v[i] == pivot_value: - v[i], v[next_value] = v[next_value], v[i] - next_value += 1 + low, mid, high = 0, 0, len(v) - 1 + while mid <= high: + if v[mid] < pivot_value: + v[low], v[mid] = v[mid], v[low] + low += 1 + mid += 1 + elif v[mid] > pivot_value: + v[mid], v[high] = v[high], v[mid] + high -= 1 + else: + mid += 1 @staticmethod def max_n(v: List[int], n: int) -> List[int]: - """Find the maximum n numbers in a list - - Args: - v (List[int]): List of integers - n (int): Number of maximum values to find - - Returns: - List[int]: List of maximum n values - """ - tmp = v.copy() - ret = [-maxsize - 1] * n - for i in range(n): - max_val = tmp[0] - max_idx = 0 - for j in range(1, len(tmp)): - if tmp[j] > max_val: - max_val = tmp[j] - max_idx = j - ret[i] = max_val - tmp.pop(max_idx) - return ret + return heapq.nlargest(n, v) \ No newline at end of file diff --git a/src/llm_benchmark/control/double.py b/src/llm_benchmark/control/double.py index 4be41d7..12d34a4 100644 --- a/src/llm_benchmark/control/double.py +++ b/src/llm_benchmark/control/double.py @@ -1,3 +1,4 @@ +from collections import Counter from typing import List @@ -14,9 +15,7 @@ def sum_square(n: int) -> int: """ sum_ = 0 for i in range(n): - for j in range(n): - if i == j: - sum_ += i * j + sum_ += i * i return sum_ @staticmethod @@ -31,8 +30,7 @@ def sum_triangle(n: int) -> int: """ sum_ = 0 for i in range(n): - for j in range(i + 1): - sum_ += j + sum_ += (i * (i + 1)) // 2 return sum_ @staticmethod @@ -47,16 +45,13 @@ def count_pairs(arr: List[int]) -> int: Returns: int: Number of pairs in the array """ + from collections import Counter count = 0 - for i in range(len(arr)): - ndup = 0 - for j in range(len(arr)): - if arr[i] == arr[j]: - ndup += 1 - if ndup == 2: + freq = Counter(arr) + for value in freq.values(): + if value == 2: count += 1 - - return count // 2 + return count @staticmethod def count_duplicates(arr0: List[int], arr1: List[int]) -> int: @@ -70,10 +65,10 @@ def count_duplicates(arr0: List[int], arr1: List[int]) -> int: int: Number of duplicates between the two arrays """ count = 0 - for i in range(len(arr0)): - for j in range(len(arr1)): - if i == j and arr0[i] == arr1[j]: - count += 1 + min_len = min(len(arr0), len(arr1)) + for i in range(min_len): + if arr0[i] == arr1[i]: + count += 1 return count @staticmethod @@ -86,8 +81,4 @@ def sum_matrix(m: List[List[int]]) -> int: Returns: int: Sum of matrix of integers """ - sum_ = 0 - for i in range(len(m)): - for j in range(len(m[i])): - sum_ += m[i][j] - return sum_ + return sum(sum(row) for row in m) \ No newline at end of file diff --git a/src/llm_benchmark/datastructures/dslist.py b/src/llm_benchmark/datastructures/dslist.py index d282a9c..7abb6fd 100644 --- a/src/llm_benchmark/datastructures/dslist.py +++ b/src/llm_benchmark/datastructures/dslist.py @@ -4,102 +4,25 @@ class DsList: @staticmethod def modify_list(v: List[int]) -> List[int]: - """Modify a list by adding 1 to each element - - Args: - v (List[int]): List of integers - - Returns: - List[int]: Modified list of integers - """ - ret = [] - for i in range(len(v)): - ret.append(v[i] + 1) - return ret + return [x + 1 for x in v] @staticmethod def search_list(v: List[int], n: int) -> List[int]: - """Search a list for a value, returning a list - of indices where the value is found - - Args: - v (List[int]): List of integers - n (int): Value to search for - - Returns: - List[int]: List of indices where the value is found - """ - ret = [] - for i in range(len(v)): - if v[i] == n: - ret.append(i) - return ret + return [i for i, x in enumerate(v) if x == n] @staticmethod def sort_list(v: List[int]) -> List[int]: - """Sort a list of integers, returns a copy - - Args: - v (List[int]): List of integers - - Returns: - List[int]: Sorted list of integers - """ - ret = v.copy() - for i in range(len(ret)): - for j in range(i + 1, len(ret)): - if ret[i] > ret[j]: - ret[i], ret[j] = ret[j], ret[i] - - return ret + return sorted(v) @staticmethod def reverse_list(v: List[int]) -> List[int]: - """Reverse a list of integers, returns a copy - - Args: - v (List[int]): List of integers - - Returns: - List[int]: Reversed list of integers - """ - ret = [] - for i in range(len(v)): - ret.append(v[len(v) - 1 - i]) - return ret + return v[::-1] @staticmethod def rotate_list(v: List[int], n: int) -> List[int]: - """Rotate a list of integers by n positions - - Args: - v (List[int]): List of integers - n (int): Number of positions to rotate - - Returns: - List[int]: Rotated list of integers - """ - ret = [] - for i in range(n, len(v)): - ret.append(v[i]) - for i in range(n): - ret.append(v[i]) - return ret + n = n % len(v) # Ensure n is within the bounds of the list length + return v[n:] + v[:n] @staticmethod def merge_lists(v1: List[int], v2: List[int]) -> List[int]: - """Merge two lists of integers, returns a copy - - Args: - v1 (List[int]): First list of integers - v2 (List[int]): Second list of integers - - Returns: - List[int]: Merged list of integers - """ - ret = [] - for i in range(len(v1)): - ret.append(v1[i]) - for i in range(len(v2)): - ret.append(v2[i]) - return ret + return v1 + v2 \ No newline at end of file diff --git a/src/llm_benchmark/sql/query.py b/src/llm_benchmark/sql/query.py index 53f6885..f24a6d7 100644 --- a/src/llm_benchmark/sql/query.py +++ b/src/llm_benchmark/sql/query.py @@ -13,11 +13,10 @@ def query_album(name: str) -> bool: Returns: bool: True if the album exists, False otherwise """ - conn = sqlite3.connect("data/chinook.db") - cur = conn.cursor() - - cur.execute(f"SELECT * FROM Album WHERE Title = '{name}'") - return len(cur.fetchall()) > 0 + with sqlite3.connect("data/chinook.db") as conn: + cur = conn.cursor() + cur.execute("SELECT 1 FROM Album WHERE Title = ?", (name,)) + return cur.fetchone() is not None @staticmethod def join_albums() -> list: @@ -26,30 +25,23 @@ def join_albums() -> list: Returns: list: """ - conn = sqlite3.connect("data/chinook.db") - cur = conn.cursor() - - cur.execute( - dedent( - """\ - SELECT - t.Name AS TrackName, ( - SELECT a2.Title - FROM Album a2 - WHERE a2.AlbumId = t.AlbumId - ) AS AlbumName, - ( - SELECT ar.Name - FROM Artist ar - JOIN Album a3 ON a3.ArtistId = ar.ArtistId - WHERE a3.AlbumId = t.AlbumId - ) AS ArtistName - FROM - Track t - """ + with sqlite3.connect("data/chinook.db") as conn: + cur = conn.cursor() + cur.execute( + dedent( + """ + SELECT + t.Name AS TrackName, + a.Title AS AlbumName, + ar.Name AS ArtistName + FROM + Track t + JOIN Album a ON a.AlbumId = t.AlbumId + JOIN Artist ar ON ar.ArtistId = a.ArtistId + """ + ) ) - ) - return cur.fetchall() + return cur.fetchall() @staticmethod def top_invoices() -> list: @@ -58,21 +50,21 @@ def top_invoices() -> list: Returns: list: List of tuples """ - conn = sqlite3.connect("data/chinook.db") - cur = conn.cursor() - - cur.execute( - dedent( - """\ - SELECT - i.InvoiceId, - c.FirstName || ' ' || c.LastName AS CustomerName, - i.Total - FROM - Invoice i - JOIN Customer c ON c.CustomerId = i.CustomerId - ORDER BY i.Total DESC - """ + with sqlite3.connect("data/chinook.db") as conn: + cur = conn.cursor() + cur.execute( + dedent( + """ + SELECT + i.InvoiceId, + c.FirstName || ' ' || c.LastName AS CustomerName, + i.Total + FROM + Invoice i + JOIN Customer c ON c.CustomerId = i.CustomerId + ORDER BY i.Total DESC + LIMIT 10 + """ + ) ) - ) - return cur.fetchall()[:10] + return cur.fetchall() \ No newline at end of file diff --git a/src/llm_benchmark/strings/strops.py b/src/llm_benchmark/strings/strops.py index b969f2e..d85b2ed 100644 --- a/src/llm_benchmark/strings/strops.py +++ b/src/llm_benchmark/strings/strops.py @@ -9,10 +9,7 @@ def str_reverse(s: str) -> str: Returns: str: Reversed string """ - ret = "" - for i in range(len(s)): - ret += s[len(s) - 1 - i] - return ret + return s[::-1] @staticmethod def palindrome(s: str) -> bool: @@ -24,7 +21,4 @@ def palindrome(s: str) -> bool: Returns: bool: True if the string is a palindrome, False otherwise """ - for i in range(len(s)): - if s[i] != s[len(s) - 1 - i]: - return False - return True + return s == s[::-1] \ No newline at end of file diff --git a/tests/llm_benchmark/datastructures/test_dslist.py b/tests/llm_benchmark/datastructures/test_dslist.py index e06bcf3..0c4749f 100644 --- a/tests/llm_benchmark/datastructures/test_dslist.py +++ b/tests/llm_benchmark/datastructures/test_dslist.py @@ -1,10 +1,7 @@ from typing import List - import pytest - from llm_benchmark.datastructures.dslist import DsList - @pytest.mark.parametrize( "v, ref", [ @@ -18,11 +15,9 @@ def test_modify_list(v: List[int], ref: List[int]) -> None: assert DsList.modify_list(v) == ref - def test_benchmark_modify_list(benchmark) -> None: benchmark(DsList.modify_list, [1, 2, 3, 4, 5]) - @pytest.mark.parametrize( "v, search_value, ref", [ @@ -34,11 +29,9 @@ def test_benchmark_modify_list(benchmark) -> None: def test_search_list(v: List[int], search_value: int, ref: List[int]) -> None: assert DsList.search_list(v, search_value) == ref - def test_benchmark_search_list(benchmark) -> None: benchmark(DsList.search_list, [1, 2, 3, 4, 5], 2) - @pytest.mark.parametrize( "v, ref", [ @@ -49,11 +42,9 @@ def test_benchmark_search_list(benchmark) -> None: def test_sort_list(v: List[int], ref: List[int]) -> None: assert DsList.sort_list(v) == ref - def test_benchmark_sort_list(benchmark) -> None: benchmark(DsList.sort_list, [5, 4, 3, 2, 1]) - @pytest.mark.parametrize( "v, ref", [ @@ -65,6 +56,5 @@ def test_benchmark_sort_list(benchmark) -> None: def test_reverse_list(v: List[int], ref: List[int]) -> None: assert DsList.reverse_list(v) == ref - def test_benchmark_reverse_list(benchmark) -> None: - benchmark(DsList.reverse_list, [1, 2, 3, 4, 5]) + benchmark(DsList.reverse_list, [1, 2, 3, 4, 5]) \ No newline at end of file