2727
2828from __future__ import annotations
2929
30- from collections .abc import Callable
30+ from collections .abc import Callable , Iterable
3131from typing import Any
3232
3333
34- def _find_run (
35- arr : list , start : int , end : int , key : Callable [[Any ], Any ] | None = None
34+ def _find_run [ T ] (
35+ arr : list [ T ] , start : int , end : int , key : Callable [[Any ], Any ] | None = None
3636) -> int :
3737 """
3838 Detect a run (ascending or descending sequence) starting at 'start'.
@@ -134,8 +134,8 @@ def _node_power(total_length: int, b1: int, n1: int, b2: int, n2: int) -> int:
134134 return power
135135
136136
137- def _merge (
138- arr : list ,
137+ def _merge [ T ] (
138+ arr : list [ T ] ,
139139 start1 : int ,
140140 end1 : int ,
141141 end2 : int ,
@@ -196,12 +196,12 @@ def _merge(
196196 k += 1
197197
198198
199- def power_sort (
200- collection : list ,
199+ def power_sort [ T ] (
200+ collection : Iterable [ T ] ,
201201 * ,
202202 key : Callable [[Any ], Any ] | None = None ,
203203 reverse : bool = False ,
204- ) -> list :
204+ ) -> list [ T ] :
205205 """
206206 Sort a list using the PowerSort algorithm.
207207
@@ -243,6 +243,8 @@ def power_sort(
243243 ['apple', 'banana', 'cherry']
244244 >>> power_sort([3.14, 2.71, 1.41, 1.73])
245245 [1.41, 1.73, 2.71, 3.14]
246+ >>> power_sort(value for value in [3, 1, 2])
247+ [1, 2, 3]
246248 >>> power_sort([5, 2, 8, 1, 9], reverse=True)
247249 [9, 8, 5, 2, 1]
248250 >>> power_sort(['apple', 'pie', 'a', 'longer'], key=len)
@@ -257,12 +259,16 @@ def power_sort(
257259 >>> result = power_sort(list(reversed(range(50))))
258260 >>> result == list(range(50))
259261 True
262+ >>> power_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
263+ Traceback (most recent call last):
264+ ...
265+ TypeError: '<' not supported between instances of 'str' and 'int'
260266 """
261- if len (collection ) <= 1 :
262- return collection
263-
264- # Make a copy to avoid modifying the original if it's immutable
267+ # Make a copy so any iterable is accepted and the original is not modified.
265268 arr = list (collection )
269+ if len (arr ) <= 1 :
270+ return arr
271+
266272 total_length = len (arr )
267273
268274 # Adjust key function for reverse sorting
0 commit comments