Skip to content

Commit fa4644b

Browse files
committed
refactor(sorts): make wiggle_sort work with comparable types
1 parent 215c1f0 commit fa4644b

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

‎sorts/wiggle_sort.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,18 @@
88
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
99
"""
1010

11+
from __future__ import annotations
1112

12-
def wiggle_sort(nums: list) -> list:
13+
from typing import Any, Protocol
14+
15+
16+
class Comparable(Protocol):
17+
def __lt__(self, other: Any, /) -> bool: ...
18+
19+
def __gt__(self, other: Any, /) -> bool: ...
20+
21+
22+
def wiggle_sort[T: Comparable](nums: list[T]) -> list[T]:
1323
"""
1424
Python implementation of wiggle sort.
1525
Reorders an array such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
@@ -23,6 +33,12 @@ def wiggle_sort(nums: list) -> list:
2333
[-5, -2, -45]
2434
>>> wiggle_sort([-2.1, -5.68, -45.11])
2535
[-5.68, -2.1, -45.11]
36+
>>> wiggle_sort(["d", "a", "c", "b"])
37+
['a', 'd', 'b', 'c']
38+
>>> wiggle_sort([1, "a"])
39+
Traceback (most recent call last):
40+
...
41+
TypeError: '>' not supported between instances of 'int' and 'str'
2642
"""
2743
for i in range(1, len(nums)):
2844
if (i % 2 == 1 and nums[i - 1] > nums[i]) or (

0 commit comments

Comments
 (0)