find_current_element
is a poor name,find_first_nonemptyfind_nonempty
would better describe what it's doing.find_current_element
is a strange form of iteration where you constantly resume the function from where it left off. This would be better described using a generator function.- Your function is good as you're swapping items in the list rather than
list.insert(0, value)
. - You don't need to invert the list twice as you can just work backwards, appending to the end.
- Since we can do this by mutating the original list, I won't return the new list.
def find_non_emptyfind_nonempty(values, is_empty):
for i in reversed(range(len(values))):
if not is_empty(values[i]):
yield i
def push(values, is_empty):
good_index = len(values) - 1
for i in find_non_emptyfind_nonempty(values, is_empty):
values[i], values[good_index] = values[good_index], values[i]
good_index -= 1
>>> list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "]
>>> push(list_, lambda i: i == " ")
>>> list_
[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']
Personally I would just use two list comprehensions, if I were to not use list.sort
, as the logic would be much clearer.
def push(values, is_empty):
return (
[v for v in values if is_empty(v)]
+ [v for v in values if not is_empty(v)]
)