Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,7 @@
* [Sol1](project_euler/problem_009/sol1.py)
* [Sol2](project_euler/problem_009/sol2.py)
* [Sol3](project_euler/problem_009/sol3.py)
* [Sol4](project_euler/problem_009/sol4.py)
* Problem 010
* [Sol1](project_euler/problem_010/sol1.py)
* [Sol2](project_euler/problem_010/sol2.py)
Expand Down Expand Up @@ -1266,6 +1267,7 @@
* [Comb Sort](sorts/comb_sort.py)
* [Counting Sort](sorts/counting_sort.py)
* [Cycle Sort](sorts/cycle_sort.py)
* [Cyclic Sort](sorts/cyclic_sort.py)
* [Double Sort](sorts/double_sort.py)
* [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py)
* [Exchange Sort](sorts/exchange_sort.py)
Expand Down
2 changes: 1 addition & 1 deletion knapsack/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# A naive recursive implementation of 0-1 Knapsack Problem
# A recursive implementation of 0-N Knapsack Problem

This overview is taken from:

Expand Down
65 changes: 43 additions & 22 deletions knapsack/knapsack.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
"""A naive recursive implementation of 0-1 Knapsack Problem
"""A recursive implementation of 0-N Knapsack Problem
https://en.wikipedia.org/wiki/Knapsack_problem
"""

from __future__ import annotations

from functools import lru_cache

def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:

def knapsack(
capacity: int,
weights: list[int],
values: list[int],
counter: int,
allow_repetition=False,
) -> int:
"""
Returns the maximum value that can be put in a knapsack of a capacity cap,
whereby each weight w has a specific value val.
whereby each weight w has a specific value val
with option to allow repetitive selection of items

>>> cap = 50
>>> val = [60, 100, 120]
Expand All @@ -17,28 +26,40 @@ def knapsack(capacity: int, weights: list[int], values: list[int], counter: int)
>>> knapsack(cap, w, val, c)
220

The result is 220 cause the values of 100 and 120 got the weight of 50
Given the repetition is NOT allowed,
the result is 220 cause the values of 100 and 120 got the weight of 50
which is the limit of the capacity.
>>> knapsack(cap, w, val, c, True)
300

Given the repetition is allowed,
the result is 300 cause the values of 60*5 (pick 5 times)
got the weight of 10*5 which is the limit of the capacity.
"""

# Base Case
if counter == 0 or capacity == 0:
return 0

# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the maximum of two cases:
# (1) nth item included
# (2) not included
if weights[counter - 1] > capacity:
return knapsack(capacity, weights, values, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack(
left_capacity, weights, values, counter - 1
)
without_new_value = knapsack(capacity, weights, values, counter - 1)
return max(new_value_included, without_new_value)
@lru_cache
def knapsack_recur(capacity: int, counter: int) -> int:
# Base Case
if counter == 0 or capacity == 0:
return 0

# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the maximum of two cases:
# (1) nth item included only once (0-1), if allow_repetition is False
# nth item included one or more times (0-N), if allow_repetition is True
# (2) not included
if weights[counter - 1] > capacity:
return knapsack_recur(capacity, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack_recur(
left_capacity, counter - 1 if not allow_repetition else counter
)
without_new_value = knapsack_recur(capacity, counter - 1)
return max(new_value_included, without_new_value)

return knapsack_recur(capacity, counter)


if __name__ == "__main__":
Expand Down
12 changes: 11 additions & 1 deletion knapsack/tests/test_knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_base_case(self):

def test_easy_case(self):
"""
test for the base case
test for the easy case
"""
cap = 3
val = [1, 2, 3]
Expand All @@ -48,6 +48,16 @@ def test_knapsack(self):
c = len(val)
assert k.knapsack(cap, w, val, c) == 220

def test_knapsack_repetition(self):
"""
test for the knapsack repetition
"""
cap = 50
val = [60, 100, 120]
w = [10, 20, 30]
c = len(val)
assert k.knapsack(cap, w, val, c, True) == 300


if __name__ == "__main__":
unittest.main()
60 changes: 60 additions & 0 deletions project_euler/problem_009/sol4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Project Euler Problem 9: https://projecteuler.net/problem=9

Special Pythagorean triplet

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2.

For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

References:
- https://en.wikipedia.org/wiki/Pythagorean_triple
"""


def get_squares(n: int) -> list[int]:
"""
>>> get_squares(0)
[]
>>> get_squares(1)
[0]
>>> get_squares(2)
[0, 1]
>>> get_squares(3)
[0, 1, 4]
>>> get_squares(4)
[0, 1, 4, 9]
"""
return [number * number for number in range(n)]


def solution(n: int = 1000) -> int:
"""
Precomputing squares and checking if a^2 + b^2 is the square by set look-up.

>>> solution(12)
60
>>> solution(36)
1620
"""

squares = get_squares(n)
squares_set = set(squares)
for a in range(1, n // 3):
for b in range(a + 1, (n - a) // 2 + 1):
if (
squares[a] + squares[b] in squares_set
and squares[n - a - b] == squares[a] + squares[b]
):
return a * b * (n - a - b)

return -1


if __name__ == "__main__":
print(f"{solution() = }")
55 changes: 55 additions & 0 deletions sorts/cyclic_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
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

doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(*cyclic_sort(unsorted), sep=",")