Skip to content

Wiggle wiggle #11681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
78 changes: 38 additions & 40 deletions sorts/dutch_national_flag_sort.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
"""
A pure implementation of Dutch national flag (DNF) sort algorithm in Python.
Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra.
It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can
sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a
single pass.
Originally designed by Edsger Dijkstra, it optimally sorts a sequence of three unique values

Check failure on line 3 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/dutch_national_flag_sort.py:3:89: E501 Line too long (93 > 88)

Check failure on line 3 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

sorts/dutch_national_flag_sort.py:3:93: W291 Trailing whitespace
(e.g., 0, 1, 2) with [0 <= a[i] <= 2] in O(n) complexity in a single pass.

The flag of the Netherlands consists of three colors: white, red, and blue.
The task is to randomly arrange balls of white, red, and blue in such a way that balls
of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear
time that does not consume any extra space. This algorithm can be implemented only on
a sequence that contains three unique elements.
The task is to randomly arrange balls of white, red, and blue so that balls of the same color

Check failure on line 6 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/dutch_national_flag_sort.py:6:89: E501 Line too long (94 > 88)

Check failure on line 6 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

sorts/dutch_national_flag_sort.py:6:94: W291 Trailing whitespace
are grouped together. DNF sorts a sequence of 0, 1, and 2's in linear time without consuming

Check failure on line 7 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/dutch_national_flag_sort.py:7:89: E501 Line too long (93 > 88)

Check failure on line 7 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

sorts/dutch_national_flag_sort.py:7:93: W291 Trailing whitespace
extra space. The algorithm works only on sequences with three unique elements.

1) Time complexity is O(n).
2) Space complexity is O(1).

More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
For more info: https://en.wikipedia.org/wiki/Dutch_national_flag_problem

For doctests run following command:
For doctests run:
python3 -m doctest -v dutch_national_flag_sort.py

For manual testing run:
python dnf_sort.py
"""

# Python program to sort a sequence containing only 0, 1 and 2 in a single pass.
red = 0 # The first color of the flag.
white = 1 # The second color of the flag.
blue = 2 # The third color of the flag.
colors = (red, white, blue)
# Python program to sort a sequence containing only 0, 1, and 2 in a single pass.
RED = 0 # The first color (red).
WHITE = 1 # The second color (white).
BLUE = 2 # The third color (blue).
ALLOWED_VALUES = (RED, WHITE, BLUE)


def dutch_national_flag_sort(sequence: list) -> list:
"""
A pure Python implementation of Dutch National Flag sort algorithm.
:param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence
:return: The same collection in ascending order
A Python implementation of the Dutch National Flag sorting algorithm.
:param sequence: A list of integers containing only 0, 1, and 2
:return: Sorted sequence with the values 0, 1, 2 in ascending order

>>> dutch_national_flag_sort([])
[]
Expand All @@ -47,52 +43,54 @@
>>> dutch_national_flag_sort("abacab")
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
>>> dutch_national_flag_sort("Abacab")
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
ValueError: The elements inside the sequence must contain only (0, 1, 2) values
>>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
ValueError: The elements inside the sequence must contain only (0, 1, 2) values
>>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
ValueError: The elements inside the sequence must contain only (0, 1, 2) values
>>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
ValueError: The elements inside the sequence must contain only (0, 1, 2) values
"""
if not sequence:
return []
if len(sequence) == 1:
return list(sequence)
low = 0
high = len(sequence) - 1
mid = 0
return sequence

low, mid, high = 0, 0, len(sequence) - 1

while mid <= high:
if sequence[mid] == colors[0]:
if sequence[mid] == RED:
sequence[low], sequence[mid] = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
elif sequence[mid] == WHITE:
mid += 1
elif sequence[mid] == colors[2]:
elif sequence[mid] == BLUE:
sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1
else:
msg = f"The elements inside the sequence must contains only {colors} values"
raise ValueError(msg)
raise ValueError(f"The elements inside the sequence must contain only {ALLOWED_VALUES} values")

Check failure on line 78 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (EM102)

sorts/dutch_national_flag_sort.py:78:30: EM102 Exception must not use an f-string literal, assign to variable first

Check failure on line 78 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/dutch_national_flag_sort.py:78:89: E501 Line too long (107 > 88)

Check failure on line 79 in sorts/dutch_national_flag_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/dutch_national_flag_sort.py:79:1: W293 Blank line contains whitespace
return sequence


if __name__ == "__main__":
import doctest

doctest.testmod()

user_input = input("Enter numbers separated by commas:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
print(f"{dutch_national_flag_sort(unsorted)}")
# User input for manual testing
user_input = input("Enter numbers separated by commas (0, 1, 2 only):\n").strip()
try:
unsorted = [int(item.strip()) for item in user_input.split(",")]
if all(x in ALLOWED_VALUES for x in unsorted):
print(f"Sorted sequence: {dutch_national_flag_sort(unsorted)}")
else:
print("Error: Input must only contain the values 0, 1, and 2.")
except ValueError:
print("Error: Invalid input. Please enter integers only.")
27 changes: 14 additions & 13 deletions sorts/wiggle_sort.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
"""
Wiggle Sort.

Given an unsorted array nums, reorder it such
that nums[0] < nums[1] > nums[2] < nums[3]....
Given an unsorted array nums, reorder it such that:
nums[0] < nums[1] > nums[2] < nums[3]....

For example:
if input numbers = [3, 5, 2, 1, 6, 4]
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
One possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""


def wiggle_sort(nums: list) -> list:
"""
Python implementation of wiggle.
Example:
Python implementation of Wiggle Sort.

Check failure on line 15 in sorts/wiggle_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/wiggle_sort.py:15:1: W293 Blank line contains whitespace
>>> wiggle_sort([0, 5, 3, 2, 2])
[0, 5, 2, 3, 2]
>>> wiggle_sort([])
Expand All @@ -22,17 +22,18 @@
>>> wiggle_sort([-2.1, -5.68, -45.11])
[-45.11, -2.1, -5.68]
"""
for i, _ in enumerate(nums):
for i in range(1, len(nums)):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]

return nums


if __name__ == "__main__":
print("Enter the array elements:")
array = list(map(int, input().split()))
print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array))
try:
user_input = input("Enter the array elements (space-separated integers):\n").strip()
array = list(map(int, user_input.split()))
print("The unsorted array is:", array)
print("Array after Wiggle sort:", wiggle_sort(array))
except ValueError:
print("Error: Please enter valid integers.")
Loading